
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_CN">
  <head>
    <meta charset="utf-8" />
    <title>内置类型 &#8212; Python 3.7.8 文档</title>
    <link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/language_data.js"></script>
    <script type="text/javascript" src="../_static/translations.js"></script>
    
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    
    <link rel="search" type="application/opensearchdescription+xml"
          title="在 Python 3.7.8 文档 中搜索"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="关于这些文档" href="../about.html" />
    <link rel="index" title="索引" href="../genindex.html" />
    <link rel="search" title="搜索" href="../search.html" />
    <link rel="copyright" title="版权所有" href="../copyright.html" />
    <link rel="next" title="内置异常" href="exceptions.html" />
    <link rel="prev" title="内置常量" href="constants.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/3/library/stdtypes.html" />
    
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
    
    
    
    <style>
      @media only screen {
        table.full-width-table {
            width: 100%;
        }
      }
    </style>
 

  </head><body>
  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>导航</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="总目录"
             accesskey="I">索引</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python 模块索引"
             >模块</a> |</li>
        <li class="right" >
          <a href="exceptions.html" title="内置异常"
             accesskey="N">下一页</a> |</li>
        <li class="right" >
          <a href="constants.html" title="内置常量"
             accesskey="P">上一页</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">3.7.8 Documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python 标准库</a> &#187;</li>
    <li class="right">
        

    <div class="inline-search" style="display: none" role="search">
        <form class="inline-search" action="../search.html" method="get">
          <input placeholder="快速搜索" type="text" name="q" />
          <input type="submit" value="转向" />
          <input type="hidden" name="check_keywords" value="yes" />
          <input type="hidden" name="area" value="default" />
        </form>
    </div>
    <script type="text/javascript">$('.inline-search').show(0);</script>
         |
    </li>

      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="built-in-types">
<span id="bltin-types"></span><h1>内置类型<a class="headerlink" href="#built-in-types" title="永久链接至标题">¶</a></h1>
<p>以下部分描述了解释器中内置的标准类型。</p>
<p id="index-0">主要内置类型有数字、序列、映射、类、实例和异常。</p>
<p>有些多项集类是可变的。 它们用于添加、移除或重排其成员的方法将原地执行，并不返回特定的项，绝对不会返回多项集实例自身而是返回 <code class="docutils literal notranslate"><span class="pre">None</span></code>。</p>
<p>有些操作受多种对象类型的支持；特别地，实际上所有对象都可以被比较、检测逻辑值，以及转换为字符串（使用 <a class="reference internal" href="functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a> 函数或略有差异的 <a class="reference internal" href="#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> 函数）。 后一个函数是在对象由 <a class="reference internal" href="functions.html#print" title="print"><code class="xref py py-func docutils literal notranslate"><span class="pre">print()</span></code></a> 函数输出时被隐式地调用的。</p>
<div class="section" id="truth-value-testing">
<span id="truth"></span><h2>逻辑值检测<a class="headerlink" href="#truth-value-testing" title="永久链接至标题">¶</a></h2>
<p id="index-1">任何对象都可以进行逻辑值的检测，以便在 <a class="reference internal" href="../reference/compound_stmts.html#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> 或 <a class="reference internal" href="../reference/compound_stmts.html#while"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">while</span></code></a> 作为条件或是作为下文所述布尔运算的操作数来使用。</p>
<p id="index-2">一个对象在默认情况下均被视为真值，除非当该对象被调用时其所属类定义了 <a class="reference internal" href="../reference/datamodel.html#object.__bool__" title="object.__bool__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__bool__()</span></code></a> 方法且返回 <code class="docutils literal notranslate"><span class="pre">False</span></code> 或是定义了 <a class="reference internal" href="../reference/datamodel.html#object.__len__" title="object.__len__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__len__()</span></code></a> 方法且返回零。 <a class="footnote-reference brackets" href="#id12" id="id1">1</a>  下面基本完整地列出了会被视为假值的内置对象:</p>
<blockquote>
<div></div></blockquote>
<ul class="simple" id="index-3">
<li><p>被定义为假值的常量: <code class="docutils literal notranslate"><span class="pre">None</span></code> 和 <code class="docutils literal notranslate"><span class="pre">False</span></code>。</p></li>
<li><p>任何数值类型的零: <code class="docutils literal notranslate"><span class="pre">0</span></code>, <code class="docutils literal notranslate"><span class="pre">0.0</span></code>, <code class="docutils literal notranslate"><span class="pre">0j</span></code>, <code class="docutils literal notranslate"><span class="pre">Decimal(0)</span></code>, <code class="docutils literal notranslate"><span class="pre">Fraction(0,</span> <span class="pre">1)</span></code></p></li>
<li><p>空的序列和多项集: <code class="docutils literal notranslate"><span class="pre">''</span></code>, <code class="docutils literal notranslate"><span class="pre">()</span></code>, <code class="docutils literal notranslate"><span class="pre">[]</span></code>, <code class="docutils literal notranslate"><span class="pre">{}</span></code>, <code class="docutils literal notranslate"><span class="pre">set()</span></code>, <code class="docutils literal notranslate"><span class="pre">range(0)</span></code></p></li>
</ul>
<p id="index-4">产生布尔值结果的运算和内置函数总是返回 <code class="docutils literal notranslate"><span class="pre">0</span></code> 或 <code class="docutils literal notranslate"><span class="pre">False</span></code> 作为假值，<code class="docutils literal notranslate"><span class="pre">1</span></code> 或 <code class="docutils literal notranslate"><span class="pre">True</span></code> 作为真值，除非另行说明。 （重要例外：布尔运算 <code class="docutils literal notranslate"><span class="pre">or</span></code> 和 <code class="docutils literal notranslate"><span class="pre">and</span></code> 总是返回其中一个操作数。）</p>
</div>
<div class="section" id="boolean-operations-and-or-not">
<span id="boolean"></span><h2>布尔运算 --- <code class="xref std std-keyword docutils literal notranslate"><span class="pre">and</span></code>, <code class="xref std std-keyword docutils literal notranslate"><span class="pre">or</span></code>, <code class="xref std std-keyword docutils literal notranslate"><span class="pre">not</span></code><a class="headerlink" href="#boolean-operations-and-or-not" title="永久链接至标题">¶</a></h2>
<p id="index-5">这些属于布尔运算，按优先级升序排列:</p>
<table class="docutils align-default">
<colgroup>
<col style="width: 25%" />
<col style="width: 62%" />
<col style="width: 13%" />
</colgroup>
<thead>
<tr class="row-odd"><th class="head"><p>运算</p></th>
<th class="head"><p>结果：</p></th>
<th class="head"><p>注释</p></th>
</tr>
</thead>
<tbody>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">or</span> <span class="pre">y</span></code></p></td>
<td><p>if <em>x</em> is false, then <em>y</em>, else
<em>x</em></p></td>
<td><p>(1)</p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">and</span> <span class="pre">y</span></code></p></td>
<td><p>if <em>x</em> is false, then <em>x</em>, else
<em>y</em></p></td>
<td><p>(2)</p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">not</span> <span class="pre">x</span></code></p></td>
<td><p>if <em>x</em> is false, then <code class="docutils literal notranslate"><span class="pre">True</span></code>,
else <code class="docutils literal notranslate"><span class="pre">False</span></code></p></td>
<td><p>(3)</p></td>
</tr>
</tbody>
</table>
<p id="index-6">注释:</p>
<ol class="arabic simple">
<li><p>这是个短路运算符，因此只有在第一个参数为假值时才会对第二个参数求值。</p></li>
<li><p>这是个短路运算符，因此只有在第一个参数为真值时才会对第二个参数求值。</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">not</span></code> 的优先级比非布尔运算符低，因此 <code class="docutils literal notranslate"><span class="pre">not</span> <span class="pre">a</span> <span class="pre">==</span> <span class="pre">b</span></code> 会被解读为 <code class="docutils literal notranslate"><span class="pre">not</span> <span class="pre">(a</span> <span class="pre">==</span> <span class="pre">b)</span></code> 而 <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">==</span> <span class="pre">not</span> <span class="pre">b</span></code> 会引发语法错误。</p></li>
</ol>
</div>
<div class="section" id="comparisons">
<span id="stdcomparisons"></span><h2>比较运算<a class="headerlink" href="#comparisons" title="永久链接至标题">¶</a></h2>
<p id="index-7">在 Python 中有八种比较运算符。 它们的优先级相同（比布尔运算的优先级高）。 比较运算可以任意串连；例如，<code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">&lt;</span> <span class="pre">y</span> <span class="pre">&lt;=</span> <span class="pre">z</span></code> 等价于 <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">&lt;</span> <span class="pre">y</span> <span class="pre">and</span> <span class="pre">y</span> <span class="pre">&lt;=</span> <span class="pre">z</span></code>，前者的不同之处在于 <em>y</em> 只被求值一次（但在两种情况下当 <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">&lt;</span> <span class="pre">y</span></code> 结果为假值时 <em>z</em> 都不会被求值）。</p>
<p>此表格汇总了比较运算:</p>
<table class="docutils align-default">
<colgroup>
<col style="width: 32%" />
<col style="width: 68%" />
</colgroup>
<thead>
<tr class="row-odd"><th class="head"><p>运算</p></th>
<th class="head"><p>含义</p></th>
</tr>
</thead>
<tbody>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">&lt;</span></code></p></td>
<td><p>严格小于</p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">&lt;=</span></code></p></td>
<td><p>小于或等于</p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">&gt;</span></code></p></td>
<td><p>严格大于</p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">&gt;=</span></code></p></td>
<td><p>大于或等于</p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">==</span></code></p></td>
<td><p>等于</p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">!=</span></code></p></td>
<td><p>不等于</p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">is</span></code></p></td>
<td><p>对象标识</p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">is</span> <span class="pre">not</span></code></p></td>
<td><p>否定的对象标识</p></td>
</tr>
</tbody>
</table>
<p id="index-8">除了不同数字类型以外，不同类型的对象比较时绝对不会相等。 而且，某些类型（例如函数对象）仅支持简化比较形式，即任何两个该种类型的对象必定不相等。 <code class="docutils literal notranslate"><span class="pre">&lt;</span></code>, <code class="docutils literal notranslate"><span class="pre">&lt;=</span></code>, <code class="docutils literal notranslate"><span class="pre">&gt;</span></code> 和 <code class="docutils literal notranslate"><span class="pre">&gt;=</span></code> 运算符在以下情况中将引发 <a class="reference internal" href="exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> 异常：当比较复数与另一个内置数字类型时，当两个对象具有无法被比较的不同类型时，或在未定义次序的其他情况时。</p>
<p id="index-9">具有不同标识的类的实例比较结果通常为不相等，除非类定义了 <a class="reference internal" href="../reference/datamodel.html#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__eq__()</span></code></a> 方法。</p>
<p>一个类实例不能与相同类或的其他实例或其他类型的对象进行排序，除非该类定义了足够多的方法，包括 <a class="reference internal" href="../reference/datamodel.html#object.__lt__" title="object.__lt__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__lt__()</span></code></a>, <a class="reference internal" href="../reference/datamodel.html#object.__le__" title="object.__le__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__le__()</span></code></a>, <a class="reference internal" href="../reference/datamodel.html#object.__gt__" title="object.__gt__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__gt__()</span></code></a> 以及 <a class="reference internal" href="../reference/datamodel.html#object.__ge__" title="object.__ge__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__ge__()</span></code></a> (而如果你想实现常规意义上的比较操作，通常只要有 <a class="reference internal" href="../reference/datamodel.html#object.__lt__" title="object.__lt__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__lt__()</span></code></a> 和 <a class="reference internal" href="../reference/datamodel.html#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__eq__()</span></code></a> 就可以了)。</p>
<p><a class="reference internal" href="../reference/expressions.html#is"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">is</span></code></a> 和 <a class="reference internal" href="../reference/expressions.html#is-not"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">is</span> <span class="pre">not</span></code></a> 运算符无法自定义；并且它们可以被应用于任意两个对象而不会引发异常。</p>
<p id="index-10">还有两种具有相同语法优先级的运算 <a class="reference internal" href="../reference/expressions.html#in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code></a> 和 <a class="reference internal" href="../reference/expressions.html#not-in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">not</span> <span class="pre">in</span></code></a>，它们被 <a class="reference internal" href="../glossary.html#term-iterable"><span class="xref std std-term">iterable</span></a> 或实现了 <a class="reference internal" href="../reference/datamodel.html#object.__contains__" title="object.__contains__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__contains__()</span></code></a> 方法的类型所支持。</p>
</div>
<div class="section" id="numeric-types-int-float-complex">
<span id="typesnumeric"></span><h2>数字类型 --- <a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a>, <a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a>, <a class="reference internal" href="functions.html#complex" title="complex"><code class="xref py py-class docutils literal notranslate"><span class="pre">complex</span></code></a><a class="headerlink" href="#numeric-types-int-float-complex" title="永久链接至标题">¶</a></h2>
<p id="index-11">存在三种不同的数字类型: <em class="dfn">整数</em>, <em class="dfn">浮点数</em> 和 <em class="dfn">复数</em>。 此外，布尔值属于整数的子类型。 整数具有无限的精度。 浮点数通常使用 C 中的 <code class="xref c c-type docutils literal notranslate"><span class="pre">double</span></code> 来实现；有关你的程序运行所在机器上浮点数的精度和内部表示法可在 <a class="reference internal" href="sys.html#sys.float_info" title="sys.float_info"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.float_info</span></code></a> 中查看。 复数包含实部和虚部，分别以一个浮点数表示。 要从一个复数 <em>z</em> 中提取这两个部分，可使用 <code class="docutils literal notranslate"><span class="pre">z.real</span></code> 和 <code class="docutils literal notranslate"><span class="pre">z.imag</span></code>。 （标准库包含附加的数字类型，如表示有理数的 <a class="reference internal" href="fractions.html#module-fractions" title="fractions: Rational numbers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">fractions</span></code></a> 以及以用户定制精度表示浮点数的 <a class="reference internal" href="decimal.html#module-decimal" title="decimal: Implementation of the General Decimal Arithmetic  Specification."><code class="xref py py-mod docutils literal notranslate"><span class="pre">decimal</span></code></a>。）</p>
<p id="index-12">数字是由数字字面值或内置函数与运算符的结果来创建的。 不带修饰的整数字面值（包括十六进制、八进制和二进制数）会生成整数。 包含小数点或幂运算符的数字字面值会生成浮点数。 在数字字面值末尾加上 <code class="docutils literal notranslate"><span class="pre">'j'</span></code> 或 <code class="docutils literal notranslate"><span class="pre">'J'</span></code> 会生成虚数（实部为零的复数），你可以将其与整数或浮点数相加来得到具有实部和虚部的复数。</p>
<p id="index-13">Python fully supports mixed arithmetic: when a binary arithmetic operator has
operands of different numeric types, the operand with the &quot;narrower&quot; type is
widened to that of the other, where integer is narrower than floating point,
which is narrower than complex. A comparison between numbers of different types
behaves as though the exact values of those numbers were being compared. <a class="footnote-reference brackets" href="#id13" id="id2">2</a></p>
<p>The constructors <a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-func docutils literal notranslate"><span class="pre">int()</span></code></a>, <a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-func docutils literal notranslate"><span class="pre">float()</span></code></a>, and
<a class="reference internal" href="functions.html#complex" title="complex"><code class="xref py py-func docutils literal notranslate"><span class="pre">complex()</span></code></a> can be used to produce numbers of a specific type.</p>
<p>所有数字类型（复数除外）都支持下列运算（有关运算优先级，请参阅：<a class="reference internal" href="../reference/expressions.html#operator-summary"><span class="std std-ref">运算符优先级</span></a>）:</p>
<table class="docutils align-default">
<colgroup>
<col style="width: 25%" />
<col style="width: 40%" />
<col style="width: 11%" />
<col style="width: 24%" />
</colgroup>
<thead>
<tr class="row-odd"><th class="head"><p>运算</p></th>
<th class="head"><p>结果：</p></th>
<th class="head"><p>注释</p></th>
<th class="head"><p>完整文档</p></th>
</tr>
</thead>
<tbody>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">+</span> <span class="pre">y</span></code></p></td>
<td><p><em>x</em> 和 <em>y</em> 的和</p></td>
<td></td>
<td></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">-</span> <span class="pre">y</span></code></p></td>
<td><p><em>x</em> 和 <em>y</em> 的差</p></td>
<td></td>
<td></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">*</span> <span class="pre">y</span></code></p></td>
<td><p><em>x</em> 和 <em>y</em> 的乘积</p></td>
<td></td>
<td></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">/</span> <span class="pre">y</span></code></p></td>
<td><p><em>x</em> 和 <em>y</em> 的商</p></td>
<td></td>
<td></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">//</span> <span class="pre">y</span></code></p></td>
<td><p><em>x</em> 和 <em>y</em> 的商数</p></td>
<td><p>(1)</p></td>
<td></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">%</span> <span class="pre">y</span></code></p></td>
<td><p>remainder of <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">/</span> <span class="pre">y</span></code></p></td>
<td><p>(2)</p></td>
<td></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">-x</span></code></p></td>
<td><p><em>x</em> 取反</p></td>
<td></td>
<td></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">+x</span></code></p></td>
<td><p><em>x</em> 不变</p></td>
<td></td>
<td></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">abs(x)</span></code></p></td>
<td><p><em>x</em> 的绝对值或大小</p></td>
<td></td>
<td><p><a class="reference internal" href="functions.html#abs" title="abs"><code class="xref py py-func docutils literal notranslate"><span class="pre">abs()</span></code></a></p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">int(x)</span></code></p></td>
<td><p>将 <em>x</em> 转换为整数</p></td>
<td><p>(3)(6)</p></td>
<td><p><a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-func docutils literal notranslate"><span class="pre">int()</span></code></a></p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">float(x)</span></code></p></td>
<td><p>将 <em>x</em> 转换为浮点数</p></td>
<td><p>(4)(6)</p></td>
<td><p><a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-func docutils literal notranslate"><span class="pre">float()</span></code></a></p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">complex(re,</span> <span class="pre">im)</span></code></p></td>
<td><p>一个带有实部 <em>re</em> 和虚部 <em>im</em> 的复数。<em>im</em> 默认为0。</p></td>
<td><p>(6)</p></td>
<td><p><a class="reference internal" href="functions.html#complex" title="complex"><code class="xref py py-func docutils literal notranslate"><span class="pre">complex()</span></code></a></p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">c.conjugate()</span></code></p></td>
<td><p>复数 <em>c</em> 的共轭</p></td>
<td></td>
<td></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">divmod(x,</span> <span class="pre">y)</span></code></p></td>
<td><p><code class="docutils literal notranslate"><span class="pre">(x</span> <span class="pre">//</span> <span class="pre">y,</span> <span class="pre">x</span> <span class="pre">%</span> <span class="pre">y)</span></code></p></td>
<td><p>(2)</p></td>
<td><p><a class="reference internal" href="functions.html#divmod" title="divmod"><code class="xref py py-func docutils literal notranslate"><span class="pre">divmod()</span></code></a></p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">pow(x,</span> <span class="pre">y)</span></code></p></td>
<td><p><em>x</em> 的 <em>y</em> 次幂</p></td>
<td><p>(5)</p></td>
<td><p><a class="reference internal" href="functions.html#pow" title="pow"><code class="xref py py-func docutils literal notranslate"><span class="pre">pow()</span></code></a></p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">**</span> <span class="pre">y</span></code></p></td>
<td><p><em>x</em> 的 <em>y</em> 次幂</p></td>
<td><p>(5)</p></td>
<td></td>
</tr>
</tbody>
</table>
<p id="index-14">注释:</p>
<ol class="arabic">
<li><p>也称为整数除法。 结果值是一个整数，但结果的类型不一定是 int。 运算结果总是向负无穷的方向舍入: <code class="docutils literal notranslate"><span class="pre">1//2</span></code> 为 <code class="docutils literal notranslate"><span class="pre">0</span></code>, <code class="docutils literal notranslate"><span class="pre">(-1)//2</span></code> 为 <code class="docutils literal notranslate"><span class="pre">-1</span></code>, <code class="docutils literal notranslate"><span class="pre">1//(-2)</span></code> 为 <code class="docutils literal notranslate"><span class="pre">-1</span></code> 而 <code class="docutils literal notranslate"><span class="pre">(-1)//(-2)</span></code> 为 <code class="docutils literal notranslate"><span class="pre">0</span></code>。</p></li>
<li><p>不可用于复数。 而应在适当条件下使用 <a class="reference internal" href="functions.html#abs" title="abs"><code class="xref py py-func docutils literal notranslate"><span class="pre">abs()</span></code></a> 转换为浮点数。</p></li>
<li><p id="index-15">从浮点数转换为整数会被舍入或是像在 C 语言中一样被截断；请参阅 <a class="reference internal" href="math.html#math.floor" title="math.floor"><code class="xref py py-func docutils literal notranslate"><span class="pre">math.floor()</span></code></a> 和 <a class="reference internal" href="math.html#math.ceil" title="math.ceil"><code class="xref py py-func docutils literal notranslate"><span class="pre">math.ceil()</span></code></a> 函数查看转换的完整定义。</p>
</li>
<li><p>float 也接受字符串 &quot;nan&quot; 和附带可选前缀 &quot;+&quot; 或 &quot;-&quot; 的 &quot;inf&quot; 分别表示非数字 (NaN) 以及正或负无穷。</p></li>
<li><p>Python 将 <code class="docutils literal notranslate"><span class="pre">pow(0,</span> <span class="pre">0)</span></code> 和 <code class="docutils literal notranslate"><span class="pre">0</span> <span class="pre">**</span> <span class="pre">0</span></code> 定义为 <code class="docutils literal notranslate"><span class="pre">1</span></code>，这是编程语言的普遍做法。</p></li>
<li><p>接受的数字字面值包括数码 <code class="docutils literal notranslate"><span class="pre">0</span></code> 到 <code class="docutils literal notranslate"><span class="pre">9</span></code> 或任何等效的 Unicode 字符（具有 <code class="docutils literal notranslate"><span class="pre">Nd</span></code> 特征属性的代码点）。</p>
<p>请参阅 <a class="reference external" href="http://www.unicode.org/Public/10.0.0/ucd/extracted/DerivedNumericType.txt">http://www.unicode.org/Public/10.0.0/ucd/extracted/DerivedNumericType.txt</a> 查看具有 <code class="docutils literal notranslate"><span class="pre">Nd</span></code> 特征属性的代码点的完整列表。</p>
</li>
</ol>
<p>所有 <a class="reference internal" href="numbers.html#numbers.Real" title="numbers.Real"><code class="xref py py-class docutils literal notranslate"><span class="pre">numbers.Real</span></code></a> 类型 (<a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a> 和 <a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a>) 还包括下列运算:</p>
<table class="docutils align-default">
<colgroup>
<col style="width: 31%" />
<col style="width: 69%" />
</colgroup>
<thead>
<tr class="row-odd"><th class="head"><p>运算</p></th>
<th class="head"><p>结果：</p></th>
</tr>
</thead>
<tbody>
<tr class="row-even"><td><p><a class="reference internal" href="math.html#math.trunc" title="math.trunc"><code class="xref py py-func docutils literal notranslate"><span class="pre">math.trunc(x)</span></code></a></p></td>
<td><p><em>x</em> 截断为 <a class="reference internal" href="numbers.html#numbers.Integral" title="numbers.Integral"><code class="xref py py-class docutils literal notranslate"><span class="pre">Integral</span></code></a></p></td>
</tr>
<tr class="row-odd"><td><p><a class="reference internal" href="functions.html#round" title="round"><code class="xref py py-func docutils literal notranslate"><span class="pre">round(x[,</span>
<span class="pre">n])</span></code></a></p></td>
<td><p><em>x</em> 舍入到 <em>n</em> 位小数，半数值会舍入到偶数。 如果省略 <em>n</em>，则默认为 0。</p></td>
</tr>
<tr class="row-even"><td><p><a class="reference internal" href="math.html#math.floor" title="math.floor"><code class="xref py py-func docutils literal notranslate"><span class="pre">math.floor(x)</span></code></a></p></td>
<td><p>&lt;= <em>x</em> 的最大 <a class="reference internal" href="numbers.html#numbers.Integral" title="numbers.Integral"><code class="xref py py-class docutils literal notranslate"><span class="pre">Integral</span></code></a></p></td>
</tr>
<tr class="row-odd"><td><p><a class="reference internal" href="math.html#math.ceil" title="math.ceil"><code class="xref py py-func docutils literal notranslate"><span class="pre">math.ceil(x)</span></code></a></p></td>
<td><p>&gt;= <em>x</em> 的最小 <a class="reference internal" href="numbers.html#numbers.Integral" title="numbers.Integral"><code class="xref py py-class docutils literal notranslate"><span class="pre">Integral</span></code></a></p></td>
</tr>
</tbody>
</table>
<p>有关更多的数字运算请参阅 <a class="reference internal" href="math.html#module-math" title="math: Mathematical functions (sin() etc.)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">math</span></code></a> 和 <a class="reference internal" href="cmath.html#module-cmath" title="cmath: Mathematical functions for complex numbers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cmath</span></code></a> 模块。</p>
<div class="section" id="bitwise-operations-on-integer-types">
<span id="bitstring-ops"></span><h3>整数类型的按位运算<a class="headerlink" href="#bitwise-operations-on-integer-types" title="永久链接至标题">¶</a></h3>
<p id="index-16">按位运算只对整数有意义。 计算按位运算的结果，就相当于使用无穷多个二进制符号位对二的补码执行操作。</p>
<p>二进制按位运算的优先级全都低于数字运算，但又高于比较运算；一元运算 <code class="docutils literal notranslate"><span class="pre">~</span></code> 具有与其他一元算术运算 (<code class="docutils literal notranslate"><span class="pre">+</span></code> and <code class="docutils literal notranslate"><span class="pre">-</span></code>) 相同的优先级。</p>
<p>此表格是以优先级升序排序的按位运算列表:</p>
<table class="docutils align-default">
<colgroup>
<col style="width: 22%" />
<col style="width: 59%" />
<col style="width: 19%" />
</colgroup>
<thead>
<tr class="row-odd"><th class="head"><p>运算</p></th>
<th class="head"><p>结果：</p></th>
<th class="head"><p>注释</p></th>
</tr>
</thead>
<tbody>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">|</span> <span class="pre">y</span></code></p></td>
<td><p><em>x</em> 和 <em>y</em> 按位 <em class="dfn">或</em></p></td>
<td><p>(4)</p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">^</span> <span class="pre">y</span></code></p></td>
<td><p><em>x</em> 和 <em>y</em> 按位 <em class="dfn">异或</em></p></td>
<td><p>(4)</p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">&amp;</span> <span class="pre">y</span></code></p></td>
<td><p><em>x</em> 和 <em>y</em> 按位 <em class="dfn">与</em></p></td>
<td><p>(4)</p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">&lt;&lt;</span> <span class="pre">n</span></code></p></td>
<td><p><em>x</em> 左移 <em>n</em> 位</p></td>
<td><p>(1)(2)</p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">&gt;&gt;</span> <span class="pre">n</span></code></p></td>
<td><p><em>x</em> 右移 <em>n</em> 位</p></td>
<td><p>(1)(3)</p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">~x</span></code></p></td>
<td><p><em>x</em> 逐位取反</p></td>
<td></td>
</tr>
</tbody>
</table>
<p>注释:</p>
<ol class="arabic simple">
<li><p>负的移位数是非法的，会导致引发 <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>。</p></li>
<li><p>A left shift by <em>n</em> bits is equivalent to multiplication by <code class="docutils literal notranslate"><span class="pre">pow(2,</span> <span class="pre">n)</span></code>.</p></li>
<li><p>A right shift by <em>n</em> bits is equivalent to floor division by <code class="docutils literal notranslate"><span class="pre">pow(2,</span> <span class="pre">n)</span></code>.</p></li>
<li><p>使用带有至少一个额外符号扩展位的有限个二进制补码表示（有效位宽度为 <code class="docutils literal notranslate"><span class="pre">1</span> <span class="pre">+</span> <span class="pre">max(x.bit_length(),</span> <span class="pre">y.bit_length())</span></code> 或以上）执行这些计算就足以获得相当于有无数个符号位时的同样结果。</p></li>
</ol>
</div>
<div class="section" id="additional-methods-on-integer-types">
<h3>整数类型的附加方法<a class="headerlink" href="#additional-methods-on-integer-types" title="永久链接至标题">¶</a></h3>
<p>int 类型实现了 <a class="reference internal" href="numbers.html#numbers.Integral" title="numbers.Integral"><code class="xref py py-class docutils literal notranslate"><span class="pre">numbers.Integral</span></code></a> <a class="reference internal" href="../glossary.html#term-abstract-base-class"><span class="xref std std-term">abstract base class</span></a>。 此外，它还提供了其他几个方法:</p>
<dl class="method">
<dt id="int.bit_length">
<code class="sig-prename descclassname">int.</code><code class="sig-name descname">bit_length</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#int.bit_length" title="永久链接至目标">¶</a></dt>
<dd><p>返回以二进制表示一个整数所需要的位数，不包括符号位和前面的零:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">n</span> <span class="o">=</span> <span class="o">-</span><span class="mi">37</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">bin</span><span class="p">(</span><span class="n">n</span><span class="p">)</span>
<span class="go">&#39;-0b100101&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">n</span><span class="o">.</span><span class="n">bit_length</span><span class="p">()</span>
<span class="go">6</span>
</pre></div>
</div>
<p>更准确地说，如果 <code class="docutils literal notranslate"><span class="pre">x</span></code> 非零，则 <code class="docutils literal notranslate"><span class="pre">x.bit_length()</span></code> 是使得 <code class="docutils literal notranslate"><span class="pre">2**(k-1)</span> <span class="pre">&lt;=</span> <span class="pre">abs(x)</span> <span class="pre">&lt;</span> <span class="pre">2**k</span></code> 的唯一正整数 <code class="docutils literal notranslate"><span class="pre">k</span></code>。 同样地，当 <code class="docutils literal notranslate"><span class="pre">abs(x)</span></code> 小到足以具有正确的舍入对数时，则 <code class="docutils literal notranslate"><span class="pre">k</span> <span class="pre">=</span> <span class="pre">1</span> <span class="pre">+</span> <span class="pre">int(log(abs(x),</span> <span class="pre">2))</span></code>。 如果 <code class="docutils literal notranslate"><span class="pre">x</span></code> 为零，则 <code class="docutils literal notranslate"><span class="pre">x.bit_length()</span></code> 返回 <code class="docutils literal notranslate"><span class="pre">0</span></code>。</p>
<p>等价于:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">bit_length</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
    <span class="n">s</span> <span class="o">=</span> <span class="nb">bin</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>       <span class="c1"># binary representation:  bin(-37) --&gt; &#39;-0b100101&#39;</span>
    <span class="n">s</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="n">lstrip</span><span class="p">(</span><span class="s1">&#39;-0b&#39;</span><span class="p">)</span> <span class="c1"># remove leading zeros and minus sign</span>
    <span class="k">return</span> <span class="nb">len</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>       <span class="c1"># len(&#39;100101&#39;) --&gt; 6</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified added">3.1 新版功能.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="int.to_bytes">
<code class="sig-prename descclassname">int.</code><code class="sig-name descname">to_bytes</code><span class="sig-paren">(</span><em class="sig-param">length</em>, <em class="sig-param">byteorder</em>, <em class="sig-param">*</em>, <em class="sig-param">signed=False</em><span class="sig-paren">)</span><a class="headerlink" href="#int.to_bytes" title="永久链接至目标">¶</a></dt>
<dd><p>返回表示一个整数的字节数组。</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="mi">1024</span><span class="p">)</span><span class="o">.</span><span class="n">to_bytes</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="n">byteorder</span><span class="o">=</span><span class="s1">&#39;big&#39;</span><span class="p">)</span>
<span class="go">b&#39;\x04\x00&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="mi">1024</span><span class="p">)</span><span class="o">.</span><span class="n">to_bytes</span><span class="p">(</span><span class="mi">10</span><span class="p">,</span> <span class="n">byteorder</span><span class="o">=</span><span class="s1">&#39;big&#39;</span><span class="p">)</span>
<span class="go">b&#39;\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="o">-</span><span class="mi">1024</span><span class="p">)</span><span class="o">.</span><span class="n">to_bytes</span><span class="p">(</span><span class="mi">10</span><span class="p">,</span> <span class="n">byteorder</span><span class="o">=</span><span class="s1">&#39;big&#39;</span><span class="p">,</span> <span class="n">signed</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="go">b&#39;\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="mi">1000</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span><span class="o">.</span><span class="n">to_bytes</span><span class="p">((</span><span class="n">x</span><span class="o">.</span><span class="n">bit_length</span><span class="p">()</span> <span class="o">+</span> <span class="mi">7</span><span class="p">)</span> <span class="o">//</span> <span class="mi">8</span><span class="p">,</span> <span class="n">byteorder</span><span class="o">=</span><span class="s1">&#39;little&#39;</span><span class="p">)</span>
<span class="go">b&#39;\xe8\x03&#39;</span>
</pre></div>
</div>
<p>整数会使用 <em>length</em> 个字节来表示。 如果整数不能用给定的字节数来表示则会引发 <a class="reference internal" href="exceptions.html#OverflowError" title="OverflowError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code></a>。</p>
<p><em>byteorder</em> 参数确定用于表示整数的字节顺序。 如果 <em>byteorder</em> 为 <code class="docutils literal notranslate"><span class="pre">&quot;big&quot;</span></code>，则最高位字节放在字节数组的开头。 如果 <em>byteorder</em> 为 <code class="docutils literal notranslate"><span class="pre">&quot;little&quot;</span></code>，则最高位字节放在字节数组的末尾。 要请求主机系统上的原生字节顺序，请使用 <a class="reference internal" href="sys.html#sys.byteorder" title="sys.byteorder"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.byteorder</span></code></a> 作为字节顺序值。</p>
<p><em>signed</em> 参数确定是否使用二的补码来表示整数。 如果 <em>signed</em> 为 <code class="docutils literal notranslate"><span class="pre">False</span></code> 并且给出的是负整数，则会引发 <a class="reference internal" href="exceptions.html#OverflowError" title="OverflowError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code></a>。 <em>signed</em> 的默认值为 <code class="docutils literal notranslate"><span class="pre">False</span></code>。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.2 新版功能.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="int.from_bytes">
<em class="property">classmethod </em><code class="sig-prename descclassname">int.</code><code class="sig-name descname">from_bytes</code><span class="sig-paren">(</span><em class="sig-param">bytes</em>, <em class="sig-param">byteorder</em>, <em class="sig-param">*</em>, <em class="sig-param">signed=False</em><span class="sig-paren">)</span><a class="headerlink" href="#int.from_bytes" title="永久链接至目标">¶</a></dt>
<dd><p>返回由给定字节数组所表示的整数。</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">int</span><span class="o">.</span><span class="n">from_bytes</span><span class="p">(</span><span class="sa">b</span><span class="s1">&#39;</span><span class="se">\x00\x10</span><span class="s1">&#39;</span><span class="p">,</span> <span class="n">byteorder</span><span class="o">=</span><span class="s1">&#39;big&#39;</span><span class="p">)</span>
<span class="go">16</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">int</span><span class="o">.</span><span class="n">from_bytes</span><span class="p">(</span><span class="sa">b</span><span class="s1">&#39;</span><span class="se">\x00\x10</span><span class="s1">&#39;</span><span class="p">,</span> <span class="n">byteorder</span><span class="o">=</span><span class="s1">&#39;little&#39;</span><span class="p">)</span>
<span class="go">4096</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">int</span><span class="o">.</span><span class="n">from_bytes</span><span class="p">(</span><span class="sa">b</span><span class="s1">&#39;</span><span class="se">\xfc\x00</span><span class="s1">&#39;</span><span class="p">,</span> <span class="n">byteorder</span><span class="o">=</span><span class="s1">&#39;big&#39;</span><span class="p">,</span> <span class="n">signed</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="go">-1024</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">int</span><span class="o">.</span><span class="n">from_bytes</span><span class="p">(</span><span class="sa">b</span><span class="s1">&#39;</span><span class="se">\xfc\x00</span><span class="s1">&#39;</span><span class="p">,</span> <span class="n">byteorder</span><span class="o">=</span><span class="s1">&#39;big&#39;</span><span class="p">,</span> <span class="n">signed</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
<span class="go">64512</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">int</span><span class="o">.</span><span class="n">from_bytes</span><span class="p">([</span><span class="mi">255</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">],</span> <span class="n">byteorder</span><span class="o">=</span><span class="s1">&#39;big&#39;</span><span class="p">)</span>
<span class="go">16711680</span>
</pre></div>
</div>
<p><em>bytes</em> 参数必须为一个 <a class="reference internal" href="../glossary.html#term-bytes-like-object"><span class="xref std std-term">bytes-like object</span></a> 或是生成字节的可迭代对象。</p>
<p><em>byteorder</em> 参数确定用于表示整数的字节顺序。 如果 <em>byteorder</em> 为 <code class="docutils literal notranslate"><span class="pre">&quot;big&quot;</span></code>，则最高位字节放在字节数组的开头。 如果 <em>byteorder</em> 为 <code class="docutils literal notranslate"><span class="pre">&quot;little&quot;</span></code>，则最高位字节放在字节数组的末尾。 要请求主机系统上的原生字节顺序，请使用 <a class="reference internal" href="sys.html#sys.byteorder" title="sys.byteorder"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.byteorder</span></code></a> 作为字节顺序值。</p>
<p><em>signed</em> 参数指明是否使用二的补码来表示整数。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.2 新版功能.</span></p>
</div>
</dd></dl>

</div>
<div class="section" id="additional-methods-on-float">
<h3>浮点类型的附加方法<a class="headerlink" href="#additional-methods-on-float" title="永久链接至标题">¶</a></h3>
<p>float 类型实现了 <a class="reference internal" href="numbers.html#numbers.Real" title="numbers.Real"><code class="xref py py-class docutils literal notranslate"><span class="pre">numbers.Real</span></code></a> <a class="reference internal" href="../glossary.html#term-abstract-base-class"><span class="xref std std-term">abstract base class</span></a>。 float 还具有以下附加方法。</p>
<dl class="method">
<dt id="float.as_integer_ratio">
<code class="sig-prename descclassname">float.</code><code class="sig-name descname">as_integer_ratio</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#float.as_integer_ratio" title="永久链接至目标">¶</a></dt>
<dd><p>返回一对整数，其比率正好等于原浮点数并且分母为正数。 无穷大会引发 <a class="reference internal" href="exceptions.html#OverflowError" title="OverflowError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code></a> 而 NaN 则会引发 <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>。</p>
</dd></dl>

<dl class="method">
<dt id="float.is_integer">
<code class="sig-prename descclassname">float.</code><code class="sig-name descname">is_integer</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#float.is_integer" title="永久链接至目标">¶</a></dt>
<dd><p>如果 float 实例可用有限位整数表示则返回 <code class="docutils literal notranslate"><span class="pre">True</span></code>，否则返回 <code class="docutils literal notranslate"><span class="pre">False</span></code>:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="o">-</span><span class="mf">2.0</span><span class="p">)</span><span class="o">.</span><span class="n">is_integer</span><span class="p">()</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="mf">3.2</span><span class="p">)</span><span class="o">.</span><span class="n">is_integer</span><span class="p">()</span>
<span class="go">False</span>
</pre></div>
</div>
</dd></dl>

<p>两个方法均支持与十六进制数字符串之间的转换。 由于 Python 浮点数在内部存储为二进制数，因此浮点数与 <em>十进制数</em> 字符串之间的转换往往会导致微小的舍入错误。 而十六进制数字符串却允许精确地表示和描述浮点数。 这在进行调试和数值工作时非常有用。</p>
<dl class="method">
<dt id="float.hex">
<code class="sig-prename descclassname">float.</code><code class="sig-name descname">hex</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#float.hex" title="永久链接至目标">¶</a></dt>
<dd><p>以十六进制字符串的形式返回一个浮点数表示。 对于有限浮点数，这种表示法将总是包含前导的 <code class="docutils literal notranslate"><span class="pre">0x</span></code> 和尾随的 <code class="docutils literal notranslate"><span class="pre">p</span></code> 加指数。</p>
</dd></dl>

<dl class="method">
<dt id="float.fromhex">
<em class="property">classmethod </em><code class="sig-prename descclassname">float.</code><code class="sig-name descname">fromhex</code><span class="sig-paren">(</span><em class="sig-param">s</em><span class="sig-paren">)</span><a class="headerlink" href="#float.fromhex" title="永久链接至目标">¶</a></dt>
<dd><p>返回以十六进制字符串 <em>s</em> 表示的浮点数的类方法。 字符串 <em>s</em> 可以带有前导和尾随的空格。</p>
</dd></dl>

<p>请注意 <a class="reference internal" href="#float.hex" title="float.hex"><code class="xref py py-meth docutils literal notranslate"><span class="pre">float.hex()</span></code></a> 是实例方法，而 <a class="reference internal" href="#float.fromhex" title="float.fromhex"><code class="xref py py-meth docutils literal notranslate"><span class="pre">float.fromhex()</span></code></a> 是类方法。</p>
<p>十六进制字符串采用的形式为:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="p">[</span><span class="n">sign</span><span class="p">]</span> <span class="p">[</span><span class="s1">&#39;0x&#39;</span><span class="p">]</span> <span class="n">integer</span> <span class="p">[</span><span class="s1">&#39;.&#39;</span> <span class="n">fraction</span><span class="p">]</span> <span class="p">[</span><span class="s1">&#39;p&#39;</span> <span class="n">exponent</span><span class="p">]</span>
</pre></div>
</div>
<p>可选的 <code class="docutils literal notranslate"><span class="pre">sign</span></code> 可以是 <code class="docutils literal notranslate"><span class="pre">+</span></code> 或 <code class="docutils literal notranslate"><span class="pre">-</span></code>，<code class="docutils literal notranslate"><span class="pre">integer</span></code> 和 <code class="docutils literal notranslate"><span class="pre">fraction</span></code> 是十六进制数码组成的字符串，<code class="docutils literal notranslate"><span class="pre">exponent</span></code> 是带有可选前导符的十进制整数。 大小写没有影响，在 integer 或 fraction 中必须至少有一个十六进制数码。 此语法类似于 C99 标准的 6.4.4.2 小节中所描述的语法，也是 Java 1.5 以上所使用的语法。 特别地，<a class="reference internal" href="#float.hex" title="float.hex"><code class="xref py py-meth docutils literal notranslate"><span class="pre">float.hex()</span></code></a> 的输出可以用作 C 或 Java 代码中的十六进制浮点数字面值，而由 C 的 <code class="docutils literal notranslate"><span class="pre">%a</span></code> 格式字符或 Java 的 <code class="docutils literal notranslate"><span class="pre">Double.toHexString</span></code> 所生成的十六进制数字符串由为 <a class="reference internal" href="#float.fromhex" title="float.fromhex"><code class="xref py py-meth docutils literal notranslate"><span class="pre">float.fromhex()</span></code></a> 所接受。</p>
<p>请注意 exponent 是十进制数而非十六进制数，它给出要与系数相乘的 2 的幂次。 例如，十六进制数字符串 <code class="docutils literal notranslate"><span class="pre">0x3.a7p10</span></code> 表示浮点数 <code class="docutils literal notranslate"><span class="pre">(3</span> <span class="pre">+</span> <span class="pre">10./16</span> <span class="pre">+</span> <span class="pre">7./16**2)</span> <span class="pre">*</span> <span class="pre">2.0**10</span></code> 即 <code class="docutils literal notranslate"><span class="pre">3740.0</span></code>:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">float</span><span class="o">.</span><span class="n">fromhex</span><span class="p">(</span><span class="s1">&#39;0x3.a7p10&#39;</span><span class="p">)</span>
<span class="go">3740.0</span>
</pre></div>
</div>
<p>对 <code class="docutils literal notranslate"><span class="pre">3740.0</span></code> 应用反向转换会得到另一个代表相同数值的十六进制数字符串:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">float</span><span class="o">.</span><span class="n">hex</span><span class="p">(</span><span class="mf">3740.0</span><span class="p">)</span>
<span class="go">&#39;0x1.d380000000000p+11&#39;</span>
</pre></div>
</div>
</div>
<div class="section" id="hashing-of-numeric-types">
<span id="numeric-hash"></span><h3>数字类型的哈希运算<a class="headerlink" href="#hashing-of-numeric-types" title="永久链接至标题">¶</a></h3>
<p>对于可能为不同类型的数字 <code class="docutils literal notranslate"><span class="pre">x</span></code> 和 <code class="docutils literal notranslate"><span class="pre">y</span></code>，要求 <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">==</span> <span class="pre">y</span></code> 时必定 <code class="docutils literal notranslate"><span class="pre">hash(x)</span> <span class="pre">==</span> <span class="pre">hash(y)</span></code> (详情参见 <a class="reference internal" href="../reference/datamodel.html#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a> 方法的文档)。 为了便于在各种数字类型 (包括 <a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a>, <a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a>, <a class="reference internal" href="decimal.html#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">decimal.Decimal</span></code></a> 和 <a class="reference internal" href="fractions.html#fractions.Fraction" title="fractions.Fraction"><code class="xref py py-class docutils literal notranslate"><span class="pre">fractions.Fraction</span></code></a>) 上实现并保证效率，Python 对数字类型的哈希运算是基于为任意有理数定义统一的数学函数，因此该运算对 <a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a> 和 <a class="reference internal" href="fractions.html#fractions.Fraction" title="fractions.Fraction"><code class="xref py py-class docutils literal notranslate"><span class="pre">fractions.Fraction</span></code></a> 的全部实例，以及 <a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a> 和 <a class="reference internal" href="decimal.html#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">decimal.Decimal</span></code></a> 的全部有限实例均可用。 从本质上说，此函数是通过以一个固定质数 <code class="docutils literal notranslate"><span class="pre">P</span></code> 进行 <code class="docutils literal notranslate"><span class="pre">P</span></code> 降模给出的。 <code class="docutils literal notranslate"><span class="pre">P</span></code> 的值在 Python 中可以 <a class="reference internal" href="sys.html#sys.hash_info" title="sys.hash_info"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.hash_info</span></code></a> 的 <code class="xref py py-attr docutils literal notranslate"><span class="pre">modulus</span></code> 属性的形式被访问。</p>
<div class="impl-detail compound">
<p><strong>CPython implementation detail:</strong> 目前所用的质数设定，在 C long 为 32 位的机器上 <code class="docutils literal notranslate"><span class="pre">P</span> <span class="pre">=</span> <span class="pre">2**31</span> <span class="pre">-</span> <span class="pre">1</span></code> 而在 C long 为 64 位的机器上 <code class="docutils literal notranslate"><span class="pre">P</span> <span class="pre">=</span> <span class="pre">2**61</span> <span class="pre">-</span> <span class="pre">1</span></code>。</p>
</div>
<p>详细规则如下所述:</p>
<ul class="simple">
<li><p>如果 <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">=</span> <span class="pre">m</span> <span class="pre">/</span> <span class="pre">n</span></code> 是一个非负的有理数且 <code class="docutils literal notranslate"><span class="pre">n</span></code> 不可被 <code class="docutils literal notranslate"><span class="pre">P</span></code> 整除，则定义 <code class="docutils literal notranslate"><span class="pre">hash(x)</span></code> 为 <code class="docutils literal notranslate"><span class="pre">m</span> <span class="pre">*</span> <span class="pre">invmod(n,</span> <span class="pre">P)</span> <span class="pre">%</span> <span class="pre">P</span></code>，其中 <code class="docutils literal notranslate"><span class="pre">invmod(n,</span> <span class="pre">P)</span></code> 是对 <code class="docutils literal notranslate"><span class="pre">n</span></code> 模 <code class="docutils literal notranslate"><span class="pre">P</span></code> 取反。</p></li>
<li><p>如果 <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">=</span> <span class="pre">m</span> <span class="pre">/</span> <span class="pre">n</span></code> 是一个非负的有理数且 <code class="docutils literal notranslate"><span class="pre">n</span></code> 可被 <code class="docutils literal notranslate"><span class="pre">P</span></code> 整除（但 <code class="docutils literal notranslate"><span class="pre">m</span></code> 不能）则 <code class="docutils literal notranslate"><span class="pre">n</span></code> 不能对 <code class="docutils literal notranslate"><span class="pre">P</span></code> 降模，以上规则不适用；在此情况下则定义 <code class="docutils literal notranslate"><span class="pre">hash(x)</span></code> 为常数值 <code class="docutils literal notranslate"><span class="pre">sys.hash_info.inf</span></code>。</p></li>
<li><p>如果 <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">=</span> <span class="pre">m</span> <span class="pre">/</span> <span class="pre">n</span></code> 是一个负的有理数则定义 <code class="docutils literal notranslate"><span class="pre">hash(x)</span></code> 为 <code class="docutils literal notranslate"><span class="pre">-hash(-x)</span></code>。 如果结果哈希值为 <code class="docutils literal notranslate"><span class="pre">-1</span></code> 则将其替换为 <code class="docutils literal notranslate"><span class="pre">-2</span></code>。</p></li>
<li><p>特定值 <code class="docutils literal notranslate"><span class="pre">sys.hash_info.inf</span></code>, <code class="docutils literal notranslate"><span class="pre">-sys.hash_info.inf</span></code> 和 <code class="docutils literal notranslate"><span class="pre">sys.hash_info.nan</span></code> 被用作正无穷、负无穷和空值（所分别对应的）哈希值。 （所有可哈希的空值都具有相同的哈希值。）</p></li>
<li><p>对于一个 <a class="reference internal" href="functions.html#complex" title="complex"><code class="xref py py-class docutils literal notranslate"><span class="pre">complex</span></code></a> 值 <code class="docutils literal notranslate"><span class="pre">z</span></code>，会通过计算 <code class="docutils literal notranslate"><span class="pre">hash(z.real)</span> <span class="pre">+</span> <span class="pre">sys.hash_info.imag</span> <span class="pre">*</span> <span class="pre">hash(z.imag)</span></code> 将实部和虚部的哈希值结合起来，并进行降模 <code class="docutils literal notranslate"><span class="pre">2**sys.hash_info.width</span></code> 以使其处于 <code class="docutils literal notranslate"><span class="pre">range(-2**(sys.hash_info.width</span> <span class="pre">-</span> <span class="pre">1),</span> <span class="pre">2**(sys.hash_info.width</span> <span class="pre">-</span> <span class="pre">1))</span></code> 范围之内。 同样地，如果结果为 <code class="docutils literal notranslate"><span class="pre">-1</span></code> 则将其替换为 <code class="docutils literal notranslate"><span class="pre">-2</span></code>。</p></li>
</ul>
<p>为了阐明上述规则，这里有一些等价于内置哈希算法的 Python 代码示例，可用于计算有理数、<a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a> 或 <a class="reference internal" href="functions.html#complex" title="complex"><code class="xref py py-class docutils literal notranslate"><span class="pre">complex</span></code></a> 的哈希值:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sys</span><span class="o">,</span> <span class="nn">math</span>

<span class="k">def</span> <span class="nf">hash_fraction</span><span class="p">(</span><span class="n">m</span><span class="p">,</span> <span class="n">n</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;Compute the hash of a rational number m / n.</span>

<span class="sd">    Assumes m and n are integers, with n positive.</span>
<span class="sd">    Equivalent to hash(fractions.Fraction(m, n)).</span>

<span class="sd">    &quot;&quot;&quot;</span>
    <span class="n">P</span> <span class="o">=</span> <span class="n">sys</span><span class="o">.</span><span class="n">hash_info</span><span class="o">.</span><span class="n">modulus</span>
    <span class="c1"># Remove common factors of P.  (Unnecessary if m and n already coprime.)</span>
    <span class="k">while</span> <span class="n">m</span> <span class="o">%</span> <span class="n">P</span> <span class="o">==</span> <span class="n">n</span> <span class="o">%</span> <span class="n">P</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
        <span class="n">m</span><span class="p">,</span> <span class="n">n</span> <span class="o">=</span> <span class="n">m</span> <span class="o">//</span> <span class="n">P</span><span class="p">,</span> <span class="n">n</span> <span class="o">//</span> <span class="n">P</span>

    <span class="k">if</span> <span class="n">n</span> <span class="o">%</span> <span class="n">P</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
        <span class="n">hash_value</span> <span class="o">=</span> <span class="n">sys</span><span class="o">.</span><span class="n">hash_info</span><span class="o">.</span><span class="n">inf</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="c1"># Fermat&#39;s Little Theorem: pow(n, P-1, P) is 1, so</span>
        <span class="c1"># pow(n, P-2, P) gives the inverse of n modulo P.</span>
        <span class="n">hash_value</span> <span class="o">=</span> <span class="p">(</span><span class="nb">abs</span><span class="p">(</span><span class="n">m</span><span class="p">)</span> <span class="o">%</span> <span class="n">P</span><span class="p">)</span> <span class="o">*</span> <span class="nb">pow</span><span class="p">(</span><span class="n">n</span><span class="p">,</span> <span class="n">P</span> <span class="o">-</span> <span class="mi">2</span><span class="p">,</span> <span class="n">P</span><span class="p">)</span> <span class="o">%</span> <span class="n">P</span>
    <span class="k">if</span> <span class="n">m</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">:</span>
        <span class="n">hash_value</span> <span class="o">=</span> <span class="o">-</span><span class="n">hash_value</span>
    <span class="k">if</span> <span class="n">hash_value</span> <span class="o">==</span> <span class="o">-</span><span class="mi">1</span><span class="p">:</span>
        <span class="n">hash_value</span> <span class="o">=</span> <span class="o">-</span><span class="mi">2</span>
    <span class="k">return</span> <span class="n">hash_value</span>

<span class="k">def</span> <span class="nf">hash_float</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;Compute the hash of a float x.&quot;&quot;&quot;</span>

    <span class="k">if</span> <span class="n">math</span><span class="o">.</span><span class="n">isnan</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
        <span class="k">return</span> <span class="n">sys</span><span class="o">.</span><span class="n">hash_info</span><span class="o">.</span><span class="n">nan</span>
    <span class="k">elif</span> <span class="n">math</span><span class="o">.</span><span class="n">isinf</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
        <span class="k">return</span> <span class="n">sys</span><span class="o">.</span><span class="n">hash_info</span><span class="o">.</span><span class="n">inf</span> <span class="k">if</span> <span class="n">x</span> <span class="o">&gt;</span> <span class="mi">0</span> <span class="k">else</span> <span class="o">-</span><span class="n">sys</span><span class="o">.</span><span class="n">hash_info</span><span class="o">.</span><span class="n">inf</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="k">return</span> <span class="n">hash_fraction</span><span class="p">(</span><span class="o">*</span><span class="n">x</span><span class="o">.</span><span class="n">as_integer_ratio</span><span class="p">())</span>

<span class="k">def</span> <span class="nf">hash_complex</span><span class="p">(</span><span class="n">z</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;Compute the hash of a complex number z.&quot;&quot;&quot;</span>

    <span class="n">hash_value</span> <span class="o">=</span> <span class="n">hash_float</span><span class="p">(</span><span class="n">z</span><span class="o">.</span><span class="n">real</span><span class="p">)</span> <span class="o">+</span> <span class="n">sys</span><span class="o">.</span><span class="n">hash_info</span><span class="o">.</span><span class="n">imag</span> <span class="o">*</span> <span class="n">hash_float</span><span class="p">(</span><span class="n">z</span><span class="o">.</span><span class="n">imag</span><span class="p">)</span>
    <span class="c1"># do a signed reduction modulo 2**sys.hash_info.width</span>
    <span class="n">M</span> <span class="o">=</span> <span class="mi">2</span><span class="o">**</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">hash_info</span><span class="o">.</span><span class="n">width</span> <span class="o">-</span> <span class="mi">1</span><span class="p">)</span>
    <span class="n">hash_value</span> <span class="o">=</span> <span class="p">(</span><span class="n">hash_value</span> <span class="o">&amp;</span> <span class="p">(</span><span class="n">M</span> <span class="o">-</span> <span class="mi">1</span><span class="p">))</span> <span class="o">-</span> <span class="p">(</span><span class="n">hash_value</span> <span class="o">&amp;</span> <span class="n">M</span><span class="p">)</span>
    <span class="k">if</span> <span class="n">hash_value</span> <span class="o">==</span> <span class="o">-</span><span class="mi">1</span><span class="p">:</span>
        <span class="n">hash_value</span> <span class="o">=</span> <span class="o">-</span><span class="mi">2</span>
    <span class="k">return</span> <span class="n">hash_value</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="iterator-types">
<span id="typeiter"></span><h2>迭代器类型<a class="headerlink" href="#iterator-types" title="永久链接至标题">¶</a></h2>
<p id="index-17">Python 支持在容器中进行迭代的概念。 这是通过使用两个单独方法来实现的；它们被用于允许用户自定义类对迭代的支持。 将在下文中详细描述的序列总是支持迭代方法。</p>
<p>容器对象要提供迭代支持，必须定义一个方法:</p>
<dl class="method">
<dt id="container.__iter__">
<code class="sig-prename descclassname">container.</code><code class="sig-name descname">__iter__</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#container.__iter__" title="永久链接至目标">¶</a></dt>
<dd><p>返回一个迭代器对象。 该对象需要支持下文所述的迭代器协议。 如果容器支持不同的迭代类型，则可以提供额外的方法来专门地请求不同迭代类型的迭代器。 （支持多种迭代形式的对象的例子有同时支持广度优先和深度优先遍历的树结构。） 此方法对应于 Python/C API 中 Python 对象类型结构体的 <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_iter" title="PyTypeObject.tp_iter"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_iter</span></code></a> 槽位。</p>
</dd></dl>

<p>迭代器对象自身需要支持以下两个方法，它们共同组成了 <em class="dfn">迭代器协议</em>:</p>
<dl class="method">
<dt id="iterator.__iter__">
<code class="sig-prename descclassname">iterator.</code><code class="sig-name descname">__iter__</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#iterator.__iter__" title="永久链接至目标">¶</a></dt>
<dd><p>返回迭代器对象本身。 这是同时允许容器和迭代器配合 <a class="reference internal" href="../reference/compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> 和 <a class="reference internal" href="../reference/expressions.html#in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code></a> 语句使用所必须的。 此方法对应于 Python/C API 中 Python 对象类型结构体的 <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_iter" title="PyTypeObject.tp_iter"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_iter</span></code></a> 槽位。</p>
</dd></dl>

<dl class="method">
<dt id="iterator.__next__">
<code class="sig-prename descclassname">iterator.</code><code class="sig-name descname">__next__</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#iterator.__next__" title="永久链接至目标">¶</a></dt>
<dd><p>从容器中返回下一项。 如果已经没有项可返回，则会引发 <a class="reference internal" href="exceptions.html#StopIteration" title="StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a> 异常。 此方法对应于 Python/C API 中 Python 对象类型结构体的 <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_iternext" title="PyTypeObject.tp_iternext"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_iternext</span></code></a> 槽位。</p>
</dd></dl>

<p>Python 定义了几种迭代器对象以支持对一般和特定序列类型、字典和其他更特别的形式进行迭代。 除了迭代器协议的实现，特定类型的其他性质对迭代操作来说都不重要。</p>
<p>一旦迭代器的 <a class="reference internal" href="#iterator.__next__" title="iterator.__next__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__next__()</span></code></a> 方法引发了 <a class="reference internal" href="exceptions.html#StopIteration" title="StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a>，它必须一直对后续调用引发同样的异常。 不遵循此行为特性的实现将无法正常使用。</p>
<div class="section" id="generator-types">
<span id="id3"></span><h3>生成器类型<a class="headerlink" href="#generator-types" title="永久链接至标题">¶</a></h3>
<p>Python 的 <a class="reference internal" href="../glossary.html#term-generator"><span class="xref std std-term">generator</span></a> 提供了一种实现迭代器协议的便捷方式。 如果容器对象 <a class="reference internal" href="../reference/datamodel.html#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a> 方法被实现为一个生成器，它将自动返回一个迭代器对象（从技术上说是一个生成器对象），该对象提供 <a class="reference internal" href="../reference/datamodel.html#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a> 和 <a class="reference internal" href="../reference/expressions.html#generator.__next__" title="generator.__next__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__next__()</span></code></a> 方法。 有关生成器的更多信息可以参阅 <a class="reference internal" href="../reference/expressions.html#yieldexpr"><span class="std std-ref">yield 表达式的文档</span></a>。</p>
</div>
</div>
<div class="section" id="sequence-types-list-tuple-range">
<span id="typesseq"></span><h2>序列类型 --- <a class="reference internal" href="#list" title="list"><code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code></a>, <a class="reference internal" href="#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a>, <a class="reference internal" href="#range" title="range"><code class="xref py py-class docutils literal notranslate"><span class="pre">range</span></code></a><a class="headerlink" href="#sequence-types-list-tuple-range" title="永久链接至标题">¶</a></h2>
<p>有三种基本序列类型：list, tuple 和 range 对象。 为处理 <a class="reference internal" href="#binaryseq"><span class="std std-ref">二进制数据</span></a> 和 <a class="reference internal" href="#textseq"><span class="std std-ref">文本字符串</span></a> 而特别定制的附加序列类型会在专门的小节中描述。</p>
<div class="section" id="common-sequence-operations">
<span id="typesseq-common"></span><h3>通用序列操作<a class="headerlink" href="#common-sequence-operations" title="永久链接至标题">¶</a></h3>
<p id="index-18">大多数序列类型，包括可变类型和不可变类型都支持下表中的操作。 <a class="reference internal" href="collections.abc.html#collections.abc.Sequence" title="collections.abc.Sequence"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.abc.Sequence</span></code></a> ABC 被提供用来更容易地在自定义序列类型上正确地实现这些操作。</p>
<p>此表按优先级升序列出了序列操作。 在表格中，<em>s</em> 和 <em>t</em> 是具有相同类型的序列，<em>n</em>, <em>i</em>, <em>j</em> 和 <em>k</em> 是整数而 <em>x</em> 是任何满足 <em>s</em> 所规定的类型和值限制的任意对象。</p>
<p><code class="docutils literal notranslate"><span class="pre">in</span></code> 和 <code class="docutils literal notranslate"><span class="pre">not</span> <span class="pre">in</span></code> 操作具有与比较操作相同的优先级。 <code class="docutils literal notranslate"><span class="pre">+</span></code> (拼接) 和 <code class="docutils literal notranslate"><span class="pre">*</span></code> (重复) 操作具有与对应数值运算相同的优先级。 <a class="footnote-reference brackets" href="#id14" id="id4">3</a></p>
<table class="docutils align-default" id="index-19">
<colgroup>
<col style="width: 38%" />
<col style="width: 47%" />
<col style="width: 15%" />
</colgroup>
<thead>
<tr class="row-odd"><th class="head"><p>运算</p></th>
<th class="head"><p>结果：</p></th>
<th class="head"><p>注释</p></th>
</tr>
</thead>
<tbody>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">in</span> <span class="pre">s</span></code></p></td>
<td><p>如果 <em>s</em> 中的某项等于 <em>x</em> 则结果为 <code class="docutils literal notranslate"><span class="pre">True</span></code>，否则为 <code class="docutils literal notranslate"><span class="pre">False</span></code></p></td>
<td><p>(1)</p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">not</span> <span class="pre">in</span> <span class="pre">s</span></code></p></td>
<td><p>如果 <em>s</em> 中的某项等于 <em>x</em> 则结果为 <code class="docutils literal notranslate"><span class="pre">False</span></code>，否则为 <code class="docutils literal notranslate"><span class="pre">True</span></code></p></td>
<td><p>(1)</p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">s</span> <span class="pre">+</span> <span class="pre">t</span></code></p></td>
<td><p><em>s</em> 与 <em>t</em> 相拼接</p></td>
<td><p>(6)(7)</p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">s</span> <span class="pre">*</span> <span class="pre">n</span></code> 或 <code class="docutils literal notranslate"><span class="pre">n</span> <span class="pre">*</span> <span class="pre">s</span></code></p></td>
<td><p>相当于 <em>s</em> 与自身进行 <em>n</em> 次拼接</p></td>
<td><p>(2)(7)</p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">s[i]</span></code></p></td>
<td><p><em>s</em> 的第 <em>i</em> 项，起始为 0</p></td>
<td><p>(3)</p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">s[i:j]</span></code></p></td>
<td><p><em>s</em> 从 <em>i</em> 到 <em>j</em> 的切片</p></td>
<td><p>(3)(4)</p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">s[i:j:k]</span></code></p></td>
<td><p><em>s</em> 从 <em>i</em> 到 <em>j</em> 步长为 <em>k</em> 的切片</p></td>
<td><p>(3)(5)</p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">len(s)</span></code></p></td>
<td><p><em>s</em> 的长度</p></td>
<td></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">min(s)</span></code></p></td>
<td><p><em>s</em> 的最小项</p></td>
<td></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">max(s)</span></code></p></td>
<td><p><em>s</em> 的最大项</p></td>
<td></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">s.index(x[,</span> <span class="pre">i[,</span> <span class="pre">j]])</span></code></p></td>
<td><p><em>x</em> 在 <em>s</em> 中首次出现项的索引号（索引号在 <em>i</em> 或其后且在 <em>j</em> 之前）</p></td>
<td><p>(8)</p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">s.count(x)</span></code></p></td>
<td><p><em>x</em> 在 <em>s</em> 中出现的总次数</p></td>
<td></td>
</tr>
</tbody>
</table>
<p>相同类型的序列也支持比较。 特别地，tuple 和 list 的比较是通过比较对应元素的字典顺序。 这意味着想要比较结果相等，则每个元素比较结果都必须相等，并且两个序列长度必须相同。 （完整细节请参阅语言参考的 <a class="reference internal" href="../reference/expressions.html#comparisons"><span class="std std-ref">比较运算</span></a> 部分。）</p>
<p>注释:</p>
<ol class="arabic">
<li><p>虽然 <code class="docutils literal notranslate"><span class="pre">in</span></code> 和 <code class="docutils literal notranslate"><span class="pre">not</span> <span class="pre">in</span></code> 操作在通常情况下仅被用于简单的成员检测，某些专门化序列 (例如 <a class="reference internal" href="#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a>, <a class="reference internal" href="#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> 和 <a class="reference internal" href="#bytearray" title="bytearray"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytearray</span></code></a>) 也使用它们进行子序列检测:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s2">&quot;gg&quot;</span> <span class="ow">in</span> <span class="s2">&quot;eggs&quot;</span>
<span class="go">True</span>
</pre></div>
</div>
</li>
<li><p>小于 <code class="docutils literal notranslate"><span class="pre">0</span></code> 的 <em>n</em> 值会被当作 <code class="docutils literal notranslate"><span class="pre">0</span></code> 来处理 (生成一个与 <em>s</em> 同类型的空序列)。 请注意序列 <em>s</em> 中的项并不会被拷贝；它们会被多次引用。 这一点经常会令 Python 编程新手感到困扰；例如:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">lists</span> <span class="o">=</span> <span class="p">[[]]</span> <span class="o">*</span> <span class="mi">3</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">lists</span>
<span class="go">[[], [], []]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">lists</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">lists</span>
<span class="go">[[3], [3], [3]]</span>
</pre></div>
</div>
<p>具体的原因在于 <code class="docutils literal notranslate"><span class="pre">[[]]</span></code> 是一个包含了一个空列表的单元素列表，所以 <code class="docutils literal notranslate"><span class="pre">[[]]</span> <span class="pre">*</span> <span class="pre">3</span></code> 结果中的三个元素都是对这一个空列表的引用。 修改 <code class="docutils literal notranslate"><span class="pre">lists</span></code> 中的任何一个元素实际上都是对这一个空列表的修改。 你可以用以下方式创建以不同列表为元素的列表:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">lists</span> <span class="o">=</span> <span class="p">[[]</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">3</span><span class="p">)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">lists</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">lists</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">lists</span><span class="p">[</span><span class="mi">2</span><span class="p">]</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">7</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">lists</span>
<span class="go">[[3], [5], [7]]</span>
</pre></div>
</div>
<p>进一步的解释可以在 FAQ 条目 <a class="reference internal" href="../faq/programming.html#faq-multidimensional-list"><span class="std std-ref">如何创建多维列表？</span></a> 中查看。</p>
</li>
<li><p>如果 <em>i</em> 或 <em>j</em> 为负值，则索引顺序是相对于序列 <em>s</em> 的末尾: 索引号会被替换为 <code class="docutils literal notranslate"><span class="pre">len(s)</span> <span class="pre">+</span> <span class="pre">i</span></code> 或 <code class="docutils literal notranslate"><span class="pre">len(s)</span> <span class="pre">+</span> <span class="pre">j</span></code>。 但要注意 <code class="docutils literal notranslate"><span class="pre">-0</span></code> 仍然为 <code class="docutils literal notranslate"><span class="pre">0</span></code>。</p></li>
<li><p><em>s</em> 从 <em>i</em> 到 <em>j</em> 的切片被定义为所有满足 <code class="docutils literal notranslate"><span class="pre">i</span> <span class="pre">&lt;=</span> <span class="pre">k</span> <span class="pre">&lt;</span> <span class="pre">j</span></code> 的索引号 <em>k</em> 的项组成的序列。 如果 <em>i</em> 或 <em>j</em> 大于 <code class="docutils literal notranslate"><span class="pre">len(s)</span></code>，则使用 <code class="docutils literal notranslate"><span class="pre">len(s)</span></code>。 如果 <em>i</em> 被省略或为 <code class="docutils literal notranslate"><span class="pre">None</span></code>，则使用 <code class="docutils literal notranslate"><span class="pre">0</span></code>。 如果 <em>j</em> 被省略或为 <code class="docutils literal notranslate"><span class="pre">None</span></code>，则使用 <code class="docutils literal notranslate"><span class="pre">len(s)</span></code>。 如果 <em>i</em> 大于等于 <em>j</em>，则切片为空。</p></li>
<li><p><em>s</em> 从 <em>i</em> 到 <em>j</em> 步长为 <em>k</em> 的切片被定义为所有满足 <code class="docutils literal notranslate"><span class="pre">0</span> <span class="pre">&lt;=</span> <span class="pre">n</span> <span class="pre">&lt;</span> <span class="pre">(j-i)/k</span></code> 的索引号  <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">=</span> <span class="pre">i</span> <span class="pre">+</span> <span class="pre">n*k</span></code> 的项组成的序列。 换句话说，索引号为 <code class="docutils literal notranslate"><span class="pre">i</span></code>, <code class="docutils literal notranslate"><span class="pre">i+k</span></code>, <code class="docutils literal notranslate"><span class="pre">i+2*k</span></code>, <code class="docutils literal notranslate"><span class="pre">i+3*k</span></code>，以此类推，当达到 <em>j</em> 时停止 (但一定不包括 <em>j</em>)。 当 <em>k</em> 为正值时，<em>i</em> 和 <em>j</em> 会被减至不大于 <code class="docutils literal notranslate"><span class="pre">len(s)</span></code>。 当 <em>k</em> 为负值时，<em>i</em> 和 <em>j</em> 会被减至不大于 <code class="docutils literal notranslate"><span class="pre">len(s)</span> <span class="pre">-</span> <span class="pre">1</span></code>。 如果 <em>i</em> 或 <em>j</em> 被省略或为 <code class="docutils literal notranslate"><span class="pre">None</span></code>，它们会成为“终止”值 (是哪一端的终止值则取决于 <em>k</em> 的符号)。 请注意，<em>k</em> 不可为零。 如果 <em>k</em> 为 <code class="docutils literal notranslate"><span class="pre">None</span></code>，则当作 <code class="docutils literal notranslate"><span class="pre">1</span></code> 处理。</p></li>
<li><p>拼接不可变序列总是会生成新的对象。 这意味着通过重复拼接来构建序列的运行时开销将会基于序列总长度的乘方。 想要获得线性的运行时开销，你必须改用下列替代方案之一：</p>
<ul class="simple">
<li><p>如果拼接 <a class="reference internal" href="#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> 对象，你可以构建一个列表并在最后使用 <a class="reference internal" href="#str.join" title="str.join"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.join()</span></code></a> 或是写入一个 <a class="reference internal" href="io.html#io.StringIO" title="io.StringIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">io.StringIO</span></code></a> 实例并在结束时获取它的值</p></li>
<li><p>如果拼接 <a class="reference internal" href="#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> 对象，你可以类似地使用 <a class="reference internal" href="#bytes.join" title="bytes.join"><code class="xref py py-meth docutils literal notranslate"><span class="pre">bytes.join()</span></code></a> 或 <a class="reference internal" href="io.html#io.BytesIO" title="io.BytesIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">io.BytesIO</span></code></a>，或者你也可以使用 <a class="reference internal" href="#bytearray" title="bytearray"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytearray</span></code></a> 对象进行原地拼接。 <a class="reference internal" href="#bytearray" title="bytearray"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytearray</span></code></a> 对象是可变的，并且具有高效的重分配机制</p></li>
<li><p>如果拼接 <a class="reference internal" href="#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a> 对象，请改为扩展 <a class="reference internal" href="#list" title="list"><code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code></a> 类</p></li>
<li><p>对于其它类型，请查看相应的文档</p></li>
</ul>
</li>
<li><p>某些序列类型 (例如 <a class="reference internal" href="#range" title="range"><code class="xref py py-class docutils literal notranslate"><span class="pre">range</span></code></a>) 仅支持遵循特定模式的项序列，因此并不支持序列拼接或重复。</p></li>
<li><p>当 <em>x</em> 在 <em>s</em> 中找不到时 <code class="docutils literal notranslate"><span class="pre">index</span></code> 会引发 <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>。 不是所有实现都支持传入额外参数 <em>i</em> 和 <em>j</em>。 这两个参数允许高效地搜索序列的子序列。 传入这两个额外参数大致相当于使用 <code class="docutils literal notranslate"><span class="pre">s[i:j].index(x)</span></code>，但是不会复制任何数据，并且返回的索引是相对于序列的开头而非切片的开头。</p></li>
</ol>
</div>
<div class="section" id="immutable-sequence-types">
<span id="typesseq-immutable"></span><h3>不可变序列类型<a class="headerlink" href="#immutable-sequence-types" title="永久链接至标题">¶</a></h3>
<p id="index-20">不可变序列类型普遍实现而可变序列类型未实现的唯一操作就是对 <a class="reference internal" href="functions.html#hash" title="hash"><code class="xref py py-func docutils literal notranslate"><span class="pre">hash()</span></code></a> 内置函数的支持。</p>
<p>这种支持允许不可变类型，例如 <a class="reference internal" href="#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a> 实例被用作 <a class="reference internal" href="#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> 键，以及存储在 <a class="reference internal" href="#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> 和 <a class="reference internal" href="#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a> 实例中。</p>
<p>尝试对包含有不可哈希值的不可变序列进行哈希运算将会导致 <a class="reference internal" href="exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>。</p>
</div>
<div class="section" id="mutable-sequence-types">
<span id="typesseq-mutable"></span><h3>可变序列类型<a class="headerlink" href="#mutable-sequence-types" title="永久链接至标题">¶</a></h3>
<p id="index-21">以下表格中的操作是在可变序列类型上定义的。 <a class="reference internal" href="collections.abc.html#collections.abc.MutableSequence" title="collections.abc.MutableSequence"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.abc.MutableSequence</span></code></a> ABC 被提供用来更容易地在自定义序列类型上正确实现这些操作。</p>
<p>表格中的 <em>s</em> 是可变序列类型的实例，<em>t</em> 是任意可迭代对象，而 <em>x</em> 是符合对 <em>s</em> 所规定类型与值限制的任何对象 (例如，<a class="reference internal" href="#bytearray" title="bytearray"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytearray</span></code></a> 仅接受满足 <code class="docutils literal notranslate"><span class="pre">0</span> <span class="pre">&lt;=</span> <span class="pre">x</span> <span class="pre">&lt;=</span> <span class="pre">255</span></code> 值限制的整数)。</p>
<table class="docutils align-default" id="index-22">
<colgroup>
<col style="width: 36%" />
<col style="width: 39%" />
<col style="width: 25%" />
</colgroup>
<thead>
<tr class="row-odd"><th class="head"><p>运算</p></th>
<th class="head"><p>结果：</p></th>
<th class="head"><p>注释</p></th>
</tr>
</thead>
<tbody>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">s[i]</span> <span class="pre">=</span> <span class="pre">x</span></code></p></td>
<td><p>将 <em>s</em> 的第 <em>i</em> 项替换为 <em>x</em></p></td>
<td></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">s[i:j]</span> <span class="pre">=</span> <span class="pre">t</span></code></p></td>
<td><p>将 <em>s</em> 从 <em>i</em> 到 <em>j</em> 的切片替换为可迭代对象 <em>t</em> 的内容</p></td>
<td></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">s[i:j]</span></code></p></td>
<td><p>等同于 <code class="docutils literal notranslate"><span class="pre">s[i:j]</span> <span class="pre">=</span> <span class="pre">[]</span></code></p></td>
<td></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">s[i:j:k]</span> <span class="pre">=</span> <span class="pre">t</span></code></p></td>
<td><p>将 <code class="docutils literal notranslate"><span class="pre">s[i:j:k]</span></code> 的元素替换为 <em>t</em> 的元素</p></td>
<td><p>(1)</p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">s[i:j:k]</span></code></p></td>
<td><p>从列表中移除 <code class="docutils literal notranslate"><span class="pre">s[i:j:k]</span></code> 的元素</p></td>
<td></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">s.append(x)</span></code></p></td>
<td><p>将 <em>x</em> 添加到序列的末尾 (等同于 <code class="docutils literal notranslate"><span class="pre">s[len(s):len(s)]</span> <span class="pre">=</span> <span class="pre">[x]</span></code>)</p></td>
<td></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">s.clear()</span></code></p></td>
<td><p>从 <em>s</em> 中移除所有项 (等同于 <code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">s[:]</span></code>)</p></td>
<td><p>(5)</p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">s.copy()</span></code></p></td>
<td><p>创建 <em>s</em> 的浅拷贝 (等同于 <code class="docutils literal notranslate"><span class="pre">s[:]</span></code>)</p></td>
<td><p>(5)</p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">s.extend(t)</span></code> 或 <code class="docutils literal notranslate"><span class="pre">s</span> <span class="pre">+=</span> <span class="pre">t</span></code></p></td>
<td><p>用 <em>t</em> 的内容扩展 <em>s</em> (基本上等同于 <code class="docutils literal notranslate"><span class="pre">s[len(s):len(s)]</span> <span class="pre">=</span> <span class="pre">t</span></code>)</p></td>
<td></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">s</span> <span class="pre">*=</span> <span class="pre">n</span></code></p></td>
<td><p>使用 <em>s</em> 的内容重复 <em>n</em> 次来对其进行更新</p></td>
<td><p>(6)</p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">s.insert(i,</span> <span class="pre">x)</span></code></p></td>
<td><p>在由 <em>i</em> 给出的索引位置将 <em>x</em> 插入 <em>s</em> (等同于 <code class="docutils literal notranslate"><span class="pre">s[i:i]</span> <span class="pre">=</span> <span class="pre">[x]</span></code>)</p></td>
<td></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">s.pop([i])</span></code></p></td>
<td><p>提取在 <em>i</em> 位置上的项，并将其从 <em>s</em> 中移除</p></td>
<td><p>(2)</p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">s.remove(x)</span></code></p></td>
<td><p>删除 <em>s</em> 中第一个 <code class="docutils literal notranslate"><span class="pre">s[i]</span></code> 等于 <em>x</em> 的项目。</p></td>
<td><p>(3)</p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">s.reverse()</span></code></p></td>
<td><p>就地将列表中的元素逆序。</p></td>
<td><p>(4)</p></td>
</tr>
</tbody>
</table>
<p>注释:</p>
<ol class="arabic">
<li><p><em>t</em> 必须与它所替换的切片具有相同的长度。</p></li>
<li><p>可选参数 <em>i</em> 默认为 <code class="docutils literal notranslate"><span class="pre">-1</span></code>，因此在默认情况下会移除并返回最后一项。</p></li>
<li><p>当在 <em>s</em> 中找不到 <em>x</em> 时 <code class="docutils literal notranslate"><span class="pre">remove</span></code> 操作会引发 <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>。</p></li>
<li><p>当反转大尺寸序列时 <code class="xref py py-meth docutils literal notranslate"><span class="pre">reverse()</span></code> 方法会原地修改该序列以保证空间经济性。 为提醒用户此操作是通过间接影响进行的，它并不会返回反转后的序列。</p></li>
<li><p>包括 <code class="xref py py-meth docutils literal notranslate"><span class="pre">clear()</span></code> 和 <code class="xref py py-meth docutils literal notranslate"><span class="pre">copy()</span></code> 是为了与不支持切片操作的可变容器 (例如 <a class="reference internal" href="#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> 和 <a class="reference internal" href="#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a>) 的接口保持一致</p>
<div class="versionadded">
<p><span class="versionmodified added">3.3 新版功能: </span><code class="xref py py-meth docutils literal notranslate"><span class="pre">clear()</span></code> 和 <code class="xref py py-meth docutils literal notranslate"><span class="pre">copy()</span></code> 方法。</p>
</div>
</li>
<li><p><em>n</em> 值为一个整数，或是一个实现了 <a class="reference internal" href="../reference/datamodel.html#object.__index__" title="object.__index__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__index__()</span></code></a> 的对象。 <em>n</em> 值为零或负数将清空序列。 序列中的项不会被拷贝；它们会被多次引用，正如 <a class="reference internal" href="#typesseq-common"><span class="std std-ref">通用序列操作</span></a> 中有关 <code class="docutils literal notranslate"><span class="pre">s</span> <span class="pre">*</span> <span class="pre">n</span></code> 的说明。</p></li>
</ol>
</div>
<div class="section" id="lists">
<span id="typesseq-list"></span><h3>列表<a class="headerlink" href="#lists" title="永久链接至标题">¶</a></h3>
<p id="index-23">列表是可变序列，通常用于存放同类项目的集合（其中精确的相似程度将根据应用而变化）。</p>
<dl class="class">
<dt id="list">
<em class="property">class </em><code class="sig-name descname">list</code><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param">iterable</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#list" title="永久链接至目标">¶</a></dt>
<dd><p>可以用多种方式构建列表：</p>
<ul class="simple">
<li><p>使用一对方括号来表示空列表: <code class="docutils literal notranslate"><span class="pre">[]</span></code></p></li>
<li><p>使用方括号，其中的项以逗号分隔: <code class="docutils literal notranslate"><span class="pre">[a]</span></code>, <code class="docutils literal notranslate"><span class="pre">[a,</span> <span class="pre">b,</span> <span class="pre">c]</span></code></p></li>
<li><p>使用列表推导式: <code class="docutils literal notranslate"><span class="pre">[x</span> <span class="pre">for</span> <span class="pre">x</span> <span class="pre">in</span> <span class="pre">iterable]</span></code></p></li>
<li><p>使用类型的构造器: <code class="docutils literal notranslate"><span class="pre">list()</span></code> 或 <code class="docutils literal notranslate"><span class="pre">list(iterable)</span></code></p></li>
</ul>
<p>构造器将构造一个列表，其中的项与 <em>iterable</em> 中的项具有相同的的值与顺序。 <em>iterable</em> 可以是序列、支持迭代的容器或其它可迭代对象。 如果 <em>iterable</em> 已经是一个列表，将创建并返回其副本，类似于 <code class="docutils literal notranslate"><span class="pre">iterable[:]</span></code>。 例如，<code class="docutils literal notranslate"><span class="pre">list('abc')</span></code> 返回 <code class="docutils literal notranslate"><span class="pre">['a',</span> <span class="pre">'b',</span> <span class="pre">'c']</span></code> 而 <code class="docutils literal notranslate"><span class="pre">list(</span> <span class="pre">(1,</span> <span class="pre">2,</span> <span class="pre">3)</span> <span class="pre">)</span></code> 返回 <code class="docutils literal notranslate"><span class="pre">[1,</span> <span class="pre">2,</span> <span class="pre">3]</span></code>。 如果没有给出参数，构造器将创建一个空列表 <code class="docutils literal notranslate"><span class="pre">[]</span></code>。</p>
<p>其它许多操作也会产生列表，包括 <a class="reference internal" href="functions.html#sorted" title="sorted"><code class="xref py py-func docutils literal notranslate"><span class="pre">sorted()</span></code></a> 内置函数。</p>
<p>列表实现了所有 <a class="reference internal" href="#typesseq-common"><span class="std std-ref">一般</span></a> 和 <a class="reference internal" href="#typesseq-mutable"><span class="std std-ref">可变</span></a> 序列的操作。 列表还额外提供了以下方法：</p>
<dl class="method">
<dt id="list.sort">
<code class="sig-name descname">sort</code><span class="sig-paren">(</span><em class="sig-param">*</em>, <em class="sig-param">key=None</em>, <em class="sig-param">reverse=False</em><span class="sig-paren">)</span><a class="headerlink" href="#list.sort" title="永久链接至目标">¶</a></dt>
<dd><p>此方法会对列表进行原地排序，只使用 <code class="docutils literal notranslate"><span class="pre">&lt;</span></code> 来进行各项间比较。 异常不会被屏蔽 —— 如果有任何比较操作失败，整个排序操作将失败（而列表可能会处于被部分修改的状态）。</p>
<p><a class="reference internal" href="#list.sort" title="list.sort"><code class="xref py py-meth docutils literal notranslate"><span class="pre">sort()</span></code></a> 接受两个仅限以关键字形式传入的参数 (<a class="reference internal" href="../glossary.html#keyword-only-parameter"><span class="std std-ref">仅限关键字参数</span></a>):</p>
<p><em>key</em> 指定带有一个参数的函数，用于从每个列表元素中提取比较键 (例如 <code class="docutils literal notranslate"><span class="pre">key=str.lower</span></code>)。 对应于列表中每一项的键会被计算一次，然后在整个排序过程中使用。 默认值 <code class="docutils literal notranslate"><span class="pre">None</span></code> 表示直接对列表项排序而不计算一个单独的键值。</p>
<p>可以使用 <a class="reference internal" href="functools.html#functools.cmp_to_key" title="functools.cmp_to_key"><code class="xref py py-func docutils literal notranslate"><span class="pre">functools.cmp_to_key()</span></code></a> 将 2.x 风格的 <em>cmp</em> 函数转换为 <em>key</em> 函数。</p>
<p><em>reverse</em> 为一个布尔值。 如果设为 <code class="docutils literal notranslate"><span class="pre">True</span></code>，则每个列表元素将按反向顺序比较进行排序。</p>
<p>当顺序大尺寸序列时此方法会原地修改该序列以保证空间经济性。 为提醒用户此操作是通过间接影响进行的，它并不会返回排序后的序列（请使用 <a class="reference internal" href="functions.html#sorted" title="sorted"><code class="xref py py-func docutils literal notranslate"><span class="pre">sorted()</span></code></a> 显示地请求一个新的已排序列表实例）。</p>
<p><a class="reference internal" href="#list.sort" title="list.sort"><code class="xref py py-meth docutils literal notranslate"><span class="pre">sort()</span></code></a> 方法确保是稳定的。 如果一个排序确保不会改变比较结果相等的元素的相对顺序就称其为稳定的 --- 这有利于进行多重排序（例如先按部门、再接薪级排序）。</p>
<div class="impl-detail compound">
<p><strong>CPython implementation detail:</strong> 在一个列表被排序期间，尝试改变甚至进行检测也会造成未定义的影响。 Python 的 C 实现会在排序期间将列表显示为空，如果发现列表在排序期间被改变将会引发 <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>。</p>
</div>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="tuples">
<span id="typesseq-tuple"></span><h3>元组<a class="headerlink" href="#tuples" title="永久链接至标题">¶</a></h3>
<p id="index-24">元组是不可变序列，通常用于储存异构数据的多项集（例如由 <a class="reference internal" href="functions.html#enumerate" title="enumerate"><code class="xref py py-func docutils literal notranslate"><span class="pre">enumerate()</span></code></a> 内置函数所产生的二元组）。 元组也被用于需要同构数据的不可变序列的情况（例如允许存储到 <a class="reference internal" href="#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> 或 <a class="reference internal" href="#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> 的实例）。</p>
<dl class="class">
<dt id="tuple">
<em class="property">class </em><code class="sig-name descname">tuple</code><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param">iterable</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#tuple" title="永久链接至目标">¶</a></dt>
<dd><p>可以用多种方式构建元组：</p>
<ul class="simple">
<li><p>使用一对圆括号来表示空元组: <code class="docutils literal notranslate"><span class="pre">()</span></code></p></li>
<li><p>使用一个后缀的逗号来表示单元组: <code class="docutils literal notranslate"><span class="pre">a,</span></code> 或 <code class="docutils literal notranslate"><span class="pre">(a,)</span></code></p></li>
<li><p>使用以逗号分隔的多个项: <code class="docutils literal notranslate"><span class="pre">a,</span> <span class="pre">b,</span> <span class="pre">c</span></code> or <code class="docutils literal notranslate"><span class="pre">(a,</span> <span class="pre">b,</span> <span class="pre">c)</span></code></p></li>
<li><p>使用内置的 <a class="reference internal" href="#tuple" title="tuple"><code class="xref py py-func docutils literal notranslate"><span class="pre">tuple()</span></code></a>: <code class="docutils literal notranslate"><span class="pre">tuple()</span></code> 或 <code class="docutils literal notranslate"><span class="pre">tuple(iterable)</span></code></p></li>
</ul>
<p>构造器将构造一个元组，其中的项与 <em>iterable</em> 中的项具有相同的值与顺序。 <em>iterable</em> 可以是序列、支持迭代的容器或其他可迭代对象。 如果 <em>iterable</em> 已经是一个元组，会不加改变地将其返回。 例如，<code class="docutils literal notranslate"><span class="pre">tuple('abc')</span></code> 返回 <code class="docutils literal notranslate"><span class="pre">('a',</span> <span class="pre">'b',</span> <span class="pre">'c')</span></code> 而 <code class="docutils literal notranslate"><span class="pre">tuple(</span> <span class="pre">[1,</span> <span class="pre">2,</span> <span class="pre">3]</span> <span class="pre">)</span></code> 返回 <code class="docutils literal notranslate"><span class="pre">(1,</span> <span class="pre">2,</span> <span class="pre">3)</span></code>。 如果没有给出参数，构造器将创建一个空元组 <code class="docutils literal notranslate"><span class="pre">()</span></code>。</p>
<p>请注意决定生成元组的其实是逗号而不是圆括号。 圆括号只是可选的，生成空元组或需要避免语法歧义的情况除外。 例如，<code class="docutils literal notranslate"><span class="pre">f(a,</span> <span class="pre">b,</span> <span class="pre">c)</span></code> 是在调用函数时附带三个参数，而 <code class="docutils literal notranslate"><span class="pre">f((a,</span> <span class="pre">b,</span> <span class="pre">c))</span></code> 则是在调用函数时附带一个三元组。</p>
<p>元组实现了所有 <a class="reference internal" href="#typesseq-common"><span class="std std-ref">一般</span></a> 序列的操作。</p>
</dd></dl>

<p>对于通过名称访问相比通过索引访问更清晰的异构数据多项集，<a class="reference internal" href="collections.html#collections.namedtuple" title="collections.namedtuple"><code class="xref py py-func docutils literal notranslate"><span class="pre">collections.namedtuple()</span></code></a> 可能是比简单元组对象更为合适的选择。</p>
</div>
<div class="section" id="ranges">
<span id="typesseq-range"></span><h3>range 对象<a class="headerlink" href="#ranges" title="永久链接至标题">¶</a></h3>
<p id="index-25"><a class="reference internal" href="#range" title="range"><code class="xref py py-class docutils literal notranslate"><span class="pre">range</span></code></a> 类型表示不可变的数字序列，通常用于在 <a class="reference internal" href="../reference/compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> 循环中循环指定的次数。</p>
<dl class="class">
<dt id="range">
<em class="property">class </em><code class="sig-name descname">range</code><span class="sig-paren">(</span><em class="sig-param">stop</em><span class="sig-paren">)</span><a class="headerlink" href="#range" title="永久链接至目标">¶</a></dt>
<dt>
<em class="property">class </em><code class="sig-name descname">range</code><span class="sig-paren">(</span><em class="sig-param">start</em>, <em class="sig-param">stop</em><span class="optional">[</span>, <em class="sig-param">step</em><span class="optional">]</span><span class="sig-paren">)</span></dt>
<dd><p>range 构造器的参数必须为整数（可以是内置的 <a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a> 或任何实现了 <code class="docutils literal notranslate"><span class="pre">__index__</span></code> 特殊方法的对象）。 如果省略 <em>step</em> 参数，其默认值为 <code class="docutils literal notranslate"><span class="pre">1</span></code>。 如果省略 <em>start</em> 参数，其默认值为 <code class="docutils literal notranslate"><span class="pre">0</span></code>，如果 <em>step</em> 为零则会引发 <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>。</p>
<p>如果 <em>step</em> 为正值，确定 range <code class="docutils literal notranslate"><span class="pre">r</span></code> 内容的公式为 <code class="docutils literal notranslate"><span class="pre">r[i]</span> <span class="pre">=</span> <span class="pre">start</span> <span class="pre">+</span> <span class="pre">step*i</span></code> 其中 <code class="docutils literal notranslate"><span class="pre">i</span> <span class="pre">&gt;=</span> <span class="pre">0</span></code> 且 <code class="docutils literal notranslate"><span class="pre">r[i]</span> <span class="pre">&lt;</span> <span class="pre">stop</span></code>。</p>
<p>如果 <em>step</em> 为负值，确定 range 内容的公式仍然为 <code class="docutils literal notranslate"><span class="pre">r[i]</span> <span class="pre">=</span> <span class="pre">start</span> <span class="pre">+</span> <span class="pre">step*i</span></code>，但限制条件改为 <code class="docutils literal notranslate"><span class="pre">i</span> <span class="pre">&gt;=</span> <span class="pre">0</span></code> 且 <code class="docutils literal notranslate"><span class="pre">r[i]</span> <span class="pre">&gt;</span> <span class="pre">stop</span></code>.</p>
<p>如果 <code class="docutils literal notranslate"><span class="pre">r[0]</span></code> 不符合值的限制条件，则该 range 对象为空。 range 对象确实支持负索引，但是会将其解读为从正索引所确定的序列的末尾开始索引。</p>
<p>元素绝对值大于 <a class="reference internal" href="sys.html#sys.maxsize" title="sys.maxsize"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.maxsize</span></code></a> 的 range 对象是被允许的，但某些特性 (例如 <a class="reference internal" href="functions.html#len" title="len"><code class="xref py py-func docutils literal notranslate"><span class="pre">len()</span></code></a>) 可能引发 <a class="reference internal" href="exceptions.html#OverflowError" title="OverflowError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code></a>。</p>
<p>一些 range 对象的例子:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">))</span>
<span class="go">[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">11</span><span class="p">))</span>
<span class="go">[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">30</span><span class="p">,</span> <span class="mi">5</span><span class="p">))</span>
<span class="go">[0, 5, 10, 15, 20, 25]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">3</span><span class="p">))</span>
<span class="go">[0, 3, 6, 9]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="o">-</span><span class="mi">10</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">))</span>
<span class="go">[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">0</span><span class="p">))</span>
<span class="go">[]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">0</span><span class="p">))</span>
<span class="go">[]</span>
</pre></div>
</div>
<p>range 对象实现了 <a class="reference internal" href="#typesseq-common"><span class="std std-ref">一般</span></a> 序列的所有操作，但拼接和重复除外（这是由于 range 对象只能表示符合严格模式的序列，而重复和拼接通常都会违反这样的模式）。</p>
<dl class="attribute">
<dt id="range.start">
<code class="sig-name descname">start</code><a class="headerlink" href="#range.start" title="永久链接至目标">¶</a></dt>
<dd><p><em>start</em> 形参的值 (如果该形参未提供则为 <code class="docutils literal notranslate"><span class="pre">0</span></code>)</p>
</dd></dl>

<dl class="attribute">
<dt id="range.stop">
<code class="sig-name descname">stop</code><a class="headerlink" href="#range.stop" title="永久链接至目标">¶</a></dt>
<dd><p><em>stop</em> 形参的值</p>
</dd></dl>

<dl class="attribute">
<dt id="range.step">
<code class="sig-name descname">step</code><a class="headerlink" href="#range.step" title="永久链接至目标">¶</a></dt>
<dd><p><em>step</em> 形参的值 (如果该形参未提供则为 <code class="docutils literal notranslate"><span class="pre">1</span></code>)</p>
</dd></dl>

</dd></dl>

<p><a class="reference internal" href="#range" title="range"><code class="xref py py-class docutils literal notranslate"><span class="pre">range</span></code></a> 类型相比常规 <a class="reference internal" href="#list" title="list"><code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code></a> 或 <a class="reference internal" href="#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a> 的优势在于一个 <a class="reference internal" href="#range" title="range"><code class="xref py py-class docutils literal notranslate"><span class="pre">range</span></code></a> 对象总是占用固定数量的（较小）内存，不论其所表示的范围有多大（因为它只保存了 <code class="docutils literal notranslate"><span class="pre">start</span></code>, <code class="docutils literal notranslate"><span class="pre">stop</span></code> 和 <code class="docutils literal notranslate"><span class="pre">step</span></code> 值，并会根据需要计算具体单项或子范围的值）。</p>
<p>range 对象实现了 <a class="reference internal" href="collections.abc.html#collections.abc.Sequence" title="collections.abc.Sequence"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.abc.Sequence</span></code></a> ABC，提供如包含检测、元素索引查找、切片等特性，并支持负索引 (参见 <a class="reference internal" href="#typesseq"><span class="std std-ref">序列类型 --- list, tuple, range</span></a>):</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">r</span> <span class="o">=</span> <span class="nb">range</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">20</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">r</span>
<span class="go">range(0, 20, 2)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="mi">11</span> <span class="ow">in</span> <span class="n">r</span>
<span class="go">False</span>
<span class="gp">&gt;&gt;&gt; </span><span class="mi">10</span> <span class="ow">in</span> <span class="n">r</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">r</span><span class="o">.</span><span class="n">index</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>
<span class="go">5</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">r</span><span class="p">[</span><span class="mi">5</span><span class="p">]</span>
<span class="go">10</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">r</span><span class="p">[:</span><span class="mi">5</span><span class="p">]</span>
<span class="go">range(0, 10, 2)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">r</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>
<span class="go">18</span>
</pre></div>
</div>
<p>使用 <code class="docutils literal notranslate"><span class="pre">==</span></code> 和 <code class="docutils literal notranslate"><span class="pre">!=</span></code> 检测 range 对象是否相等是将其作为序列来比较。 也就是说，如果两个 range 对象表示相同的值序列就认为它们是相等的。 （请注意比较结果相等的两个 range 对象可能会具有不同的 <a class="reference internal" href="#range.start" title="range.start"><code class="xref py py-attr docutils literal notranslate"><span class="pre">start</span></code></a>, <a class="reference internal" href="#range.stop" title="range.stop"><code class="xref py py-attr docutils literal notranslate"><span class="pre">stop</span></code></a> 和 <a class="reference internal" href="#range.step" title="range.step"><code class="xref py py-attr docutils literal notranslate"><span class="pre">step</span></code></a> 属性，例如 <code class="docutils literal notranslate"><span class="pre">range(0)</span> <span class="pre">==</span> <span class="pre">range(2,</span> <span class="pre">1,</span> <span class="pre">3)</span></code> 而 <code class="docutils literal notranslate"><span class="pre">range(0,</span> <span class="pre">3,</span> <span class="pre">2)</span> <span class="pre">==</span> <span class="pre">range(0,</span> <span class="pre">4,</span> <span class="pre">2)</span></code>。）</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.2 版更改: </span>实现 Sequence ABC。 支持切片和负数索引。 使用 <a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a> 对象在固定时间内进行成员检测，而不是逐一迭代所有项。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.3 版更改: </span>定义 '==' 和 '!=' 以根据 range 对象所定义的值序列来进行比较（而不是根据对象的标识）。</p>
</div>
<div class="versionadded">
<p><span class="versionmodified added">3.3 新版功能: </span><a class="reference internal" href="#range.start" title="range.start"><code class="xref py py-attr docutils literal notranslate"><span class="pre">start</span></code></a>, <a class="reference internal" href="#range.stop" title="range.stop"><code class="xref py py-attr docutils literal notranslate"><span class="pre">stop</span></code></a> 和 <a class="reference internal" href="#range.step" title="range.step"><code class="xref py py-attr docutils literal notranslate"><span class="pre">step</span></code></a> 属性。</p>
</div>
<div class="admonition seealso">
<p class="admonition-title">参见</p>
<ul class="simple">
<li><p><a class="reference external" href="http://code.activestate.com/recipes/579000/">linspace recipe</a> 演示了如何实现一个延迟求值版本的适合浮点数应用的 range 对象。</p></li>
</ul>
</div>
</div>
</div>
<div class="section" id="text-sequence-type-str">
<span id="textseq"></span><span id="index-26"></span><h2>文本序列类型 --- <a class="reference internal" href="#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a><a class="headerlink" href="#text-sequence-type-str" title="永久链接至标题">¶</a></h2>
<p>在 Python 中处理文本数据是使用 <a class="reference internal" href="#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> 对象，也称为 <em class="dfn">字符串</em>。 字符串是由 Unicode 码位构成的不可变 <a class="reference internal" href="#typesseq"><span class="std std-ref">序列</span></a>。 字符串字面值有多种不同的写法：</p>
<ul class="simple">
<li><p>单引号: <code class="docutils literal notranslate"><span class="pre">'允许包含有</span> <span class="pre">&quot;双&quot;</span> <span class="pre">引号'</span></code></p></li>
<li><p>双引号: <code class="docutils literal notranslate"><span class="pre">&quot;允许包含有</span> <span class="pre">'单'</span> <span class="pre">引号&quot;</span></code>。</p></li>
<li><p>三重引号: <code class="docutils literal notranslate"><span class="pre">'''三重单引号'''</span></code>, <code class="docutils literal notranslate"><span class="pre">&quot;&quot;&quot;三重双引号&quot;&quot;&quot;</span></code></p></li>
</ul>
<p>使用三重引号的字符串可以跨越多行 —— 其中所有的空白字符都将包含在该字符串字面值中。</p>
<p>作为单一表达式组成部分，之间只由空格分隔的多个字符串字面值会被隐式地转换为单个字符串字面值。 也就是说，<code class="docutils literal notranslate"><span class="pre">(&quot;spam</span> <span class="pre">&quot;</span> <span class="pre">&quot;eggs&quot;)</span> <span class="pre">==</span> <span class="pre">&quot;spam</span> <span class="pre">eggs&quot;</span></code>。</p>
<p>请参阅 <a class="reference internal" href="../reference/lexical_analysis.html#strings"><span class="std std-ref">字符串和字节串字面值</span></a> 有解有关不同字符串字面值的更多信息，包括所支持的转义序列，以及使用 <code class="docutils literal notranslate"><span class="pre">r</span></code> (&quot;raw&quot;) 前缀来禁用大多数转义序列的处理。</p>
<p>字符串也可以通过使用 <a class="reference internal" href="#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> 构造器从其他对象创建。</p>
<p>由于不存在单独的“字符”类型，对字符串做索引操作将产生一个长度为 1 的字符串。 也就是说，对于一个非空字符串 <em>s</em>, <code class="docutils literal notranslate"><span class="pre">s[0]</span> <span class="pre">==</span> <span class="pre">s[0:1]</span></code>。</p>
<p id="index-27">不存在可变的字符串类型，但是 <a class="reference internal" href="#str.join" title="str.join"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.join()</span></code></a> 或 <a class="reference internal" href="io.html#io.StringIO" title="io.StringIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">io.StringIO</span></code></a> 可以被被用来根据多个片段高效率地构建字符串。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.3 版更改: </span>为了与 Python 2 系列的向下兼容，再次允许字符串字面值使用 <code class="docutils literal notranslate"><span class="pre">u</span></code> 前缀。 它对字符串字面值的含义没有影响，并且不能与 <code class="docutils literal notranslate"><span class="pre">r</span></code> 前缀同时出现。</p>
</div>
<span class="target" id="index-28"></span><dl class="class">
<dt id="str">
<em class="property">class </em><code class="sig-name descname">str</code><span class="sig-paren">(</span><em class="sig-param">object=''</em><span class="sig-paren">)</span><a class="headerlink" href="#str" title="永久链接至目标">¶</a></dt>
<dt>
<em class="property">class </em><code class="sig-name descname">str</code><span class="sig-paren">(</span><em class="sig-param">object=b''</em>, <em class="sig-param">encoding='utf-8'</em>, <em class="sig-param">errors='strict'</em><span class="sig-paren">)</span></dt>
<dd><p>返回 <em>object</em> 的 <a class="reference internal" href="#textseq"><span class="std std-ref">字符串</span></a> 版本。 如果未提供 <em>object</em> 则返回空字符串。 在其他情况下 <code class="docutils literal notranslate"><span class="pre">str()</span></code> 的行为取决于 <em>encoding</em> 或 <em>errors</em> 是否有给出，具体见下。</p>
<p>如果 <em>encoding</em> 或 <em>errors</em> 均未给出，<code class="docutils literal notranslate"><span class="pre">str(object)</span></code> 返回 <a class="reference internal" href="../reference/datamodel.html#object.__str__" title="object.__str__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">object.__str__()</span></code></a>，这是 <em>object</em> 的“非正式”或格式良好的字符串表示。 对于字符串对象，这是该字符串本身。 如果 <em>object</em> 没有 <a class="reference internal" href="../reference/datamodel.html#object.__str__" title="object.__str__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__str__()</span></code></a> 方法，则 <a class="reference internal" href="#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> 将回退为返回 <a class="reference internal" href="functions.html#repr" title="repr"><code class="xref py py-meth docutils literal notranslate"><span class="pre">repr(object)</span></code></a>。</p>
<p id="index-29">如果 <em>encoding</em> 或 <em>errors</em> 至少给出其中之一，则 <em>object</em> 应该是一个 <a class="reference internal" href="../glossary.html#term-bytes-like-object"><span class="xref std std-term">bytes-like object</span></a> (例如 <a class="reference internal" href="#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> 或 <a class="reference internal" href="#bytearray" title="bytearray"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytearray</span></code></a>)。 在此情况下，如果 <em>object</em> 是一个 <a class="reference internal" href="#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> (或 <a class="reference internal" href="#bytearray" title="bytearray"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytearray</span></code></a>) 对象，则 <code class="docutils literal notranslate"><span class="pre">str(bytes,</span> <span class="pre">encoding,</span> <span class="pre">errors)</span></code> 等价于 <a class="reference internal" href="#bytes.decode" title="bytes.decode"><code class="xref py py-meth docutils literal notranslate"><span class="pre">bytes.decode(encoding,</span> <span class="pre">errors)</span></code></a>。 否则的话，会在调用 <a class="reference internal" href="#bytes.decode" title="bytes.decode"><code class="xref py py-meth docutils literal notranslate"><span class="pre">bytes.decode()</span></code></a> 之前获取缓冲区对象下层的 bytes 对象。 请参阅 <a class="reference internal" href="#binaryseq"><span class="std std-ref">二进制序列类型 --- bytes, bytearray, memoryview</span></a> 与 <a class="reference internal" href="../c-api/buffer.html#bufferobjects"><span class="std std-ref">缓冲协议</span></a> 了解有关缓冲区对象的信息。</p>
<p>将一个 <a class="reference internal" href="#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> 对象传入 <a class="reference internal" href="#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> 而不给出 <em>encoding</em> 或 <em>errors</em> 参数的操作属于第一种情况， 将返回非正式的字符串表示（另请参阅 Python 的 <a class="reference internal" href="../using/cmdline.html#cmdoption-b"><code class="xref std std-option docutils literal notranslate"><span class="pre">-b</span></code></a> 命令行选项）。 例如:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">str</span><span class="p">(</span><span class="sa">b</span><span class="s1">&#39;Zoot!&#39;</span><span class="p">)</span>
<span class="go">&quot;b&#39;Zoot!&#39;&quot;</span>
</pre></div>
</div>
<p>有关 <code class="docutils literal notranslate"><span class="pre">str</span></code> 类及其方法的更多信息，请参阅下面的 <a class="reference internal" href="#textseq"><span class="std std-ref">文本序列类型 --- str</span></a> 和 <a class="reference internal" href="#string-methods"><span class="std std-ref">字符串的方法</span></a> 小节。 要输出格式化字符串，请参阅 <a class="reference internal" href="../reference/lexical_analysis.html#f-strings"><span class="std std-ref">格式化字符串字面值</span></a> 和 <a class="reference internal" href="string.html#formatstrings"><span class="std std-ref">格式字符串语法</span></a> 小节。 此外还可以参阅 <a class="reference internal" href="text.html#stringservices"><span class="std std-ref">文本处理服务</span></a> 小节。</p>
</dd></dl>

<div class="section" id="string-methods">
<span id="index-30"></span><span id="id5"></span><h3>字符串的方法<a class="headerlink" href="#string-methods" title="永久链接至标题">¶</a></h3>
<p id="index-31">字符串实现了所有 <a class="reference internal" href="#typesseq-common"><span class="std std-ref">一般</span></a> 序列的操作，还额外提供了以下列出的一些附加方法。</p>
<p>字符串还支持两种字符串格式化样式，一种提供了很大程度的灵活性和可定制性 (参阅 <a class="reference internal" href="#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.format()</span></code></a>, <a class="reference internal" href="string.html#formatstrings"><span class="std std-ref">格式字符串语法</span></a> 和 <a class="reference internal" href="string.html#string-formatting"><span class="std std-ref">自定义字符串格式化</span></a>) 而另一种是基于 C <code class="docutils literal notranslate"><span class="pre">printf</span></code> 样式的格式化，它可处理的类型范围较窄，并且更难以正确使用，但对于它可处理的情况往往会更为快速 (<a class="reference internal" href="#old-string-formatting"><span class="std std-ref">printf 风格的字符串格式化</span></a>)。</p>
<p>标准库的 <a class="reference internal" href="text.html#textservices"><span class="std std-ref">文本处理服务</span></a> 部分涵盖了许多其他模块，提供各种文本相关工具（例如包含于 <a class="reference internal" href="re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> 模块中的正则表达式支持）。</p>
<dl class="method">
<dt id="str.capitalize">
<code class="sig-prename descclassname">str.</code><code class="sig-name descname">capitalize</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#str.capitalize" title="永久链接至目标">¶</a></dt>
<dd><p>返回原字符串的副本，其首个字符大写，其余为小写。</p>
</dd></dl>

<dl class="method">
<dt id="str.casefold">
<code class="sig-prename descclassname">str.</code><code class="sig-name descname">casefold</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#str.casefold" title="永久链接至目标">¶</a></dt>
<dd><p>返回原字符串消除大小写的副本。 消除大小写的字符串可用于忽略大小写的匹配。</p>
<p>消除大小写类似于转为小写，但是更加彻底一些，因为它会移除字符串中的所有大小写变化形式。 例如，德语小写字母 <code class="docutils literal notranslate"><span class="pre">'ß'</span></code> 相当于 <code class="docutils literal notranslate"><span class="pre">&quot;ss&quot;</span></code>。 由于它已经是小写了，<a class="reference internal" href="#str.lower" title="str.lower"><code class="xref py py-meth docutils literal notranslate"><span class="pre">lower()</span></code></a> 不会对 <code class="docutils literal notranslate"><span class="pre">'ß'</span></code> 做任何改变；而 <a class="reference internal" href="#str.casefold" title="str.casefold"><code class="xref py py-meth docutils literal notranslate"><span class="pre">casefold()</span></code></a> 则会将其转换为 <code class="docutils literal notranslate"><span class="pre">&quot;ss&quot;</span></code>。</p>
<p>消除大小写算法的描述请参见 Unicode 标准的 3.13 节。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.3 新版功能.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="str.center">
<code class="sig-prename descclassname">str.</code><code class="sig-name descname">center</code><span class="sig-paren">(</span><em class="sig-param">width</em><span class="optional">[</span>, <em class="sig-param">fillchar</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#str.center" title="永久链接至目标">¶</a></dt>
<dd><p>返回长度为 <em>width</em> 的字符串，原字符串在其正中。 使用指定的 <em>fillchar</em> 填充两边的空位（默认使用 ASCII 空格符）。 如果 <em>width</em> 小于等于 <code class="docutils literal notranslate"><span class="pre">len(s)</span></code> 则返回原字符串的副本。</p>
</dd></dl>

<dl class="method">
<dt id="str.count">
<code class="sig-prename descclassname">str.</code><code class="sig-name descname">count</code><span class="sig-paren">(</span><em class="sig-param">sub</em><span class="optional">[</span>, <em class="sig-param">start</em><span class="optional">[</span>, <em class="sig-param">end</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#str.count" title="永久链接至目标">¶</a></dt>
<dd><p>反回子字符串 <em>sub</em> 在 [<em>start</em>, <em>end</em>] 范围内非重叠出现的次数。 可选参数 <em>start</em> 与 <em>end</em> 会被解读为切片表示法。</p>
</dd></dl>

<dl class="method">
<dt id="str.encode">
<code class="sig-prename descclassname">str.</code><code class="sig-name descname">encode</code><span class="sig-paren">(</span><em class="sig-param">encoding=&quot;utf-8&quot;</em>, <em class="sig-param">errors=&quot;strict&quot;</em><span class="sig-paren">)</span><a class="headerlink" href="#str.encode" title="永久链接至目标">¶</a></dt>
<dd><p>返回原字符串编码为字节串对象的版本。 默认编码为 <code class="docutils literal notranslate"><span class="pre">'utf-8'</span></code>。 可以给出 <em>errors</em> 来设置不同的错误处理方案。 <em>errors</em> 的默认值为 <code class="docutils literal notranslate"><span class="pre">'strict'</span></code>，表示编码错误会引发 <a class="reference internal" href="exceptions.html#UnicodeError" title="UnicodeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeError</span></code></a>。 其他可用的值为 <code class="docutils literal notranslate"><span class="pre">'ignore'</span></code>, <code class="docutils literal notranslate"><span class="pre">'replace'</span></code>, <code class="docutils literal notranslate"><span class="pre">'xmlcharrefreplace'</span></code>, <code class="docutils literal notranslate"><span class="pre">'backslashreplace'</span></code> 以及任何其他通过 <a class="reference internal" href="codecs.html#codecs.register_error" title="codecs.register_error"><code class="xref py py-func docutils literal notranslate"><span class="pre">codecs.register_error()</span></code></a> 注册的值，请参阅 <a class="reference internal" href="codecs.html#error-handlers"><span class="std std-ref">错误处理方案</span></a> 小节。 要查看可用的编码列表，请参阅 <a class="reference internal" href="codecs.html#standard-encodings"><span class="std std-ref">标准编码</span></a> 小节。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.1 版更改: </span>加入了对关键字参数的支持。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="str.endswith">
<code class="sig-prename descclassname">str.</code><code class="sig-name descname">endswith</code><span class="sig-paren">(</span><em class="sig-param">suffix</em><span class="optional">[</span>, <em class="sig-param">start</em><span class="optional">[</span>, <em class="sig-param">end</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#str.endswith" title="永久链接至目标">¶</a></dt>
<dd><p>如果字符串以指定的 <em>suffix</em> 结束返回 <code class="docutils literal notranslate"><span class="pre">True</span></code>，否则返回 <code class="docutils literal notranslate"><span class="pre">False</span></code>。 <em>suffix</em> 也可以为由多个供查找的后缀构成的元组。 如果有可选项 <em>start</em>，将从所指定位置开始检查。 如果有可选项 <em>end</em>，将在所指定位置停止比较。</p>
</dd></dl>

<dl class="method">
<dt id="str.expandtabs">
<code class="sig-prename descclassname">str.</code><code class="sig-name descname">expandtabs</code><span class="sig-paren">(</span><em class="sig-param">tabsize=8</em><span class="sig-paren">)</span><a class="headerlink" href="#str.expandtabs" title="永久链接至目标">¶</a></dt>
<dd><p>返回字符串的副本，其中所有的制表符会由一个或多个空格替换，具体取决于当前列位置和给定的制表符宽度。 每 <em>tabsize</em> 个字符设为一个制表位（默认值 8 时设定的制表位在列 0, 8, 16 依次类推）。 要展开字符串，当前列将被设为零并逐一检查字符串中的每个字符。 如果字符为制表符 (<code class="docutils literal notranslate"><span class="pre">\t</span></code>)，则会在结果中插入一个或多个空格符，直到当前列等于下一个制表位。 （制表符本身不会被复制。） 如果字符为换行符 (<code class="docutils literal notranslate"><span class="pre">\n</span></code>) 或回车符 (<code class="docutils literal notranslate"><span class="pre">\r</span></code>)，它会被复制并将当前列重设为零。 任何其他字符会被不加修改地复制并将当前列加一，不论该字符在被打印时会如何显示。</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;01</span><span class="se">\t</span><span class="s1">012</span><span class="se">\t</span><span class="s1">0123</span><span class="se">\t</span><span class="s1">01234&#39;</span><span class="o">.</span><span class="n">expandtabs</span><span class="p">()</span>
<span class="go">&#39;01      012     0123    01234&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;01</span><span class="se">\t</span><span class="s1">012</span><span class="se">\t</span><span class="s1">0123</span><span class="se">\t</span><span class="s1">01234&#39;</span><span class="o">.</span><span class="n">expandtabs</span><span class="p">(</span><span class="mi">4</span><span class="p">)</span>
<span class="go">&#39;01  012 0123    01234&#39;</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="str.find">
<code class="sig-prename descclassname">str.</code><code class="sig-name descname">find</code><span class="sig-paren">(</span><em class="sig-param">sub</em><span class="optional">[</span>, <em class="sig-param">start</em><span class="optional">[</span>, <em class="sig-param">end</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#str.find" title="永久链接至目标">¶</a></dt>
<dd><p>返回子字符串 <em>sub</em> 在 <code class="docutils literal notranslate"><span class="pre">s[start:end]</span></code> 切片内被找到的最小索引。 可选参数 <em>start</em> 与 <em>end</em> 会被解读为切片表示法。 如果 <em>sub</em> 未被找到则返回 <code class="docutils literal notranslate"><span class="pre">-1</span></code>。</p>
<div class="admonition note">
<p class="admonition-title">注解</p>
<p><a class="reference internal" href="#str.find" title="str.find"><code class="xref py py-meth docutils literal notranslate"><span class="pre">find()</span></code></a> 方法应该只在你需要知道 <em>sub</em> 所在位置时使用。 要检查 <em>sub</em> 是否为子字符串，请使用 <a class="reference internal" href="../reference/expressions.html#in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code></a> 操作符:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;Py&#39;</span> <span class="ow">in</span> <span class="s1">&#39;Python&#39;</span>
<span class="go">True</span>
</pre></div>
</div>
</div>
</dd></dl>

<dl class="method">
<dt id="str.format">
<code class="sig-prename descclassname">str.</code><code class="sig-name descname">format</code><span class="sig-paren">(</span><em class="sig-param">*args</em>, <em class="sig-param">**kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#str.format" title="永久链接至目标">¶</a></dt>
<dd><p>执行字符串格式化操作。 调用此方法的字符串可以包含字符串字面值或者以花括号 <code class="docutils literal notranslate"><span class="pre">{}</span></code> 括起来的替换域。 每个替换域可以包含一个位置参数的数字索引，或者一个关键字参数的名称。 返回的字符串副本中每个替换域都会被替换为对应参数的字符串值。</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s2">&quot;The sum of 1 + 2 is </span><span class="si">{0}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="mi">1</span><span class="o">+</span><span class="mi">2</span><span class="p">)</span>
<span class="go">&#39;The sum of 1 + 2 is 3&#39;</span>
</pre></div>
</div>
<p>请参阅 <a class="reference internal" href="string.html#formatstrings"><span class="std std-ref">格式字符串语法</span></a> 了解有关可以在格式字符串中指定的各种格式选项的说明。</p>
<div class="admonition note">
<p class="admonition-title">注解</p>
<p>当使用 <code class="docutils literal notranslate"><span class="pre">n</span></code> 类型 (例如: <code class="docutils literal notranslate"><span class="pre">'{:n}'.format(1234)</span></code>) 来格式化数字 (<a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a>, <a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a>, <a class="reference internal" href="functions.html#complex" title="complex"><code class="xref py py-class docutils literal notranslate"><span class="pre">complex</span></code></a>, <a class="reference internal" href="decimal.html#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">decimal.Decimal</span></code></a> 及其子类) 的时候，该函数会临时性地将 <code class="docutils literal notranslate"><span class="pre">LC_CTYPE</span></code> 区域设置为 <code class="docutils literal notranslate"><span class="pre">LC_NUMERIC</span></code> 区域以解码  <code class="xref c c-func docutils literal notranslate"><span class="pre">localeconv()</span></code> 的 <code class="docutils literal notranslate"><span class="pre">decimal_point</span></code> 和 <code class="docutils literal notranslate"><span class="pre">thousands_sep</span></code> 字段，如果它们是非 ASCII 字符或长度超过 1 字节的话，并且 <code class="docutils literal notranslate"><span class="pre">LC_NUMERIC</span></code> 区域会与 <code class="docutils literal notranslate"><span class="pre">LC_CTYPE</span></code> 区域不一致。 这个临时更改会影响其他线程。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.7 版更改: </span>当使用 <code class="docutils literal notranslate"><span class="pre">n</span></code> 类型格式化数字时，该函数在某些情况下会临时性地将 <code class="docutils literal notranslate"><span class="pre">LC_CTYPE</span></code> 区域设置为 <code class="docutils literal notranslate"><span class="pre">LC_NUMERIC</span></code> 区域。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="str.format_map">
<code class="sig-prename descclassname">str.</code><code class="sig-name descname">format_map</code><span class="sig-paren">(</span><em class="sig-param">mapping</em><span class="sig-paren">)</span><a class="headerlink" href="#str.format_map" title="永久链接至目标">¶</a></dt>
<dd><p>类似于 <code class="docutils literal notranslate"><span class="pre">str.format(**mapping)</span></code>，不同之处在于 <code class="docutils literal notranslate"><span class="pre">mapping</span></code> 会被直接使用而不是复制到一个 <a class="reference internal" href="#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>。 适宜使用此方法的一个例子是当 <code class="docutils literal notranslate"><span class="pre">mapping</span></code> 为 dict 的子类的情况：</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">Default</span><span class="p">(</span><span class="nb">dict</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="fm">__missing__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">):</span>
<span class="gp">... </span>        <span class="k">return</span> <span class="n">key</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;</span><span class="si">{name}</span><span class="s1"> was born in </span><span class="si">{country}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format_map</span><span class="p">(</span><span class="n">Default</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;Guido&#39;</span><span class="p">))</span>
<span class="go">&#39;Guido was born in country&#39;</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified added">3.2 新版功能.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="str.index">
<code class="sig-prename descclassname">str.</code><code class="sig-name descname">index</code><span class="sig-paren">(</span><em class="sig-param">sub</em><span class="optional">[</span>, <em class="sig-param">start</em><span class="optional">[</span>, <em class="sig-param">end</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#str.index" title="永久链接至目标">¶</a></dt>
<dd><p>类似于 <a class="reference internal" href="#str.find" title="str.find"><code class="xref py py-meth docutils literal notranslate"><span class="pre">find()</span></code></a>，但在找不到子类时会引发 <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>。</p>
</dd></dl>

<dl class="method">
<dt id="str.isalnum">
<code class="sig-prename descclassname">str.</code><code class="sig-name descname">isalnum</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#str.isalnum" title="永久链接至目标">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if all characters in the string are alphanumeric and there is at
least one character, <code class="docutils literal notranslate"><span class="pre">False</span></code> otherwise.  A character <code class="docutils literal notranslate"><span class="pre">c</span></code> is alphanumeric if one
of the following returns <code class="docutils literal notranslate"><span class="pre">True</span></code>: <code class="docutils literal notranslate"><span class="pre">c.isalpha()</span></code>, <code class="docutils literal notranslate"><span class="pre">c.isdecimal()</span></code>,
<code class="docutils literal notranslate"><span class="pre">c.isdigit()</span></code>, or <code class="docutils literal notranslate"><span class="pre">c.isnumeric()</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="str.isalpha">
<code class="sig-prename descclassname">str.</code><code class="sig-name descname">isalpha</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#str.isalpha" title="永久链接至目标">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if all characters in the string are alphabetic and there is at least
one character, <code class="docutils literal notranslate"><span class="pre">False</span></code> otherwise.  Alphabetic characters are those characters defined
in the Unicode character database as &quot;Letter&quot;, i.e., those with general category
property being one of &quot;Lm&quot;, &quot;Lt&quot;, &quot;Lu&quot;, &quot;Ll&quot;, or &quot;Lo&quot;.  Note that this is different
from the &quot;Alphabetic&quot; property defined in the Unicode Standard.</p>
</dd></dl>

<dl class="method">
<dt id="str.isascii">
<code class="sig-prename descclassname">str.</code><code class="sig-name descname">isascii</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#str.isascii" title="永久链接至目标">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the string is empty or all characters in the string are ASCII,
<code class="docutils literal notranslate"><span class="pre">False</span></code> otherwise.
ASCII characters have code points in the range U+0000-U+007F.</p>
<div class="versionadded">
<p><span class="versionmodified added">3.7 新版功能.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="str.isdecimal">
<code class="sig-prename descclassname">str.</code><code class="sig-name descname">isdecimal</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#str.isdecimal" title="永久链接至目标">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if all characters in the string are decimal
characters and there is at least one character, <code class="docutils literal notranslate"><span class="pre">False</span></code>
otherwise. Decimal characters are those that can be used to form
numbers in base 10, e.g. U+0660, ARABIC-INDIC DIGIT
ZERO.  Formally a decimal character is a character in the Unicode
General Category &quot;Nd&quot;.</p>
</dd></dl>

<dl class="method">
<dt id="str.isdigit">
<code class="sig-prename descclassname">str.</code><code class="sig-name descname">isdigit</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#str.isdigit" title="永久链接至目标">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if all characters in the string are digits and there is at least one
character, <code class="docutils literal notranslate"><span class="pre">False</span></code> otherwise.  Digits include decimal characters and digits that need
special handling, such as the compatibility superscript digits.
This covers digits which cannot be used to form numbers in base 10,
like the Kharosthi numbers.  Formally, a digit is a character that has the
property value Numeric_Type=Digit or Numeric_Type=Decimal.</p>
</dd></dl>

<dl class="method">
<dt id="str.isidentifier">
<code class="sig-prename descclassname">str.</code><code class="sig-name descname">isidentifier</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#str.isidentifier" title="永久链接至目标">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the string is a valid identifier according to the language
definition, section <a class="reference internal" href="../reference/lexical_analysis.html#identifiers"><span class="std std-ref">标识符和关键字</span></a>.</p>
<p>请使用 <a class="reference internal" href="keyword.html#keyword.iskeyword" title="keyword.iskeyword"><code class="xref py py-func docutils literal notranslate"><span class="pre">keyword.iskeyword()</span></code></a> 来检测保留标识符，例如 <a class="reference internal" href="../reference/compound_stmts.html#def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">def</span></code></a> 和 <a class="reference internal" href="../reference/compound_stmts.html#class"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">class</span></code></a>。</p>
</dd></dl>

<dl class="method">
<dt id="str.islower">
<code class="sig-prename descclassname">str.</code><code class="sig-name descname">islower</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#str.islower" title="永久链接至目标">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if all cased characters <a class="footnote-reference brackets" href="#id15" id="id6">4</a> in the string are lowercase and
there is at least one cased character, <code class="docutils literal notranslate"><span class="pre">False</span></code> otherwise.</p>
</dd></dl>

<dl class="method">
<dt id="str.isnumeric">
<code class="sig-prename descclassname">str.</code><code class="sig-name descname">isnumeric</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#str.isnumeric" title="永久链接至目标">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if all characters in the string are numeric
characters, and there is at least one character, <code class="docutils literal notranslate"><span class="pre">False</span></code>
otherwise. Numeric characters include digit characters, and all characters
that have the Unicode numeric value property, e.g. U+2155,
VULGAR FRACTION ONE FIFTH.  Formally, numeric characters are those with the property
value Numeric_Type=Digit, Numeric_Type=Decimal or Numeric_Type=Numeric.</p>
</dd></dl>

<dl class="method">
<dt id="str.isprintable">
<code class="sig-prename descclassname">str.</code><code class="sig-name descname">isprintable</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#str.isprintable" title="永久链接至目标">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if all characters in the string are printable or the string is
empty, <code class="docutils literal notranslate"><span class="pre">False</span></code> otherwise.  Nonprintable characters are those characters defined
in the Unicode character database as &quot;Other&quot; or &quot;Separator&quot;, excepting the
ASCII space (0x20) which is considered printable.  (Note that printable
characters in this context are those which should not be escaped when
<a class="reference internal" href="functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a> is invoked on a string.  It has no bearing on the handling of
strings written to <a class="reference internal" href="sys.html#sys.stdout" title="sys.stdout"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.stdout</span></code></a> or <a class="reference internal" href="sys.html#sys.stderr" title="sys.stderr"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.stderr</span></code></a>.)</p>
</dd></dl>

<dl class="method">
<dt id="str.isspace">
<code class="sig-prename descclassname">str.</code><code class="sig-name descname">isspace</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#str.isspace" title="永久链接至目标">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if there are only whitespace characters in the string and there is
at least one character, <code class="docutils literal notranslate"><span class="pre">False</span></code> otherwise.</p>
<p><em>空白</em> 字符是指在 Unicode 字符数据库 (参见 <a class="reference internal" href="unicodedata.html#module-unicodedata" title="unicodedata: Access the Unicode Database."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unicodedata</span></code></a>) 中主要类别为 <code class="docutils literal notranslate"><span class="pre">Zs</span></code> (&quot;Separator, space&quot;) 或所属双向类为 <code class="docutils literal notranslate"><span class="pre">WS</span></code>, <code class="docutils literal notranslate"><span class="pre">B</span></code> 或 <code class="docutils literal notranslate"><span class="pre">S</span></code> 的字符。</p>
</dd></dl>

<dl class="method">
<dt id="str.istitle">
<code class="sig-prename descclassname">str.</code><code class="sig-name descname">istitle</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#str.istitle" title="永久链接至目标">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the string is a titlecased string and there is at least one
character, for example uppercase characters may only follow uncased characters
and lowercase characters only cased ones.  Return <code class="docutils literal notranslate"><span class="pre">False</span></code> otherwise.</p>
</dd></dl>

<dl class="method">
<dt id="str.isupper">
<code class="sig-prename descclassname">str.</code><code class="sig-name descname">isupper</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#str.isupper" title="永久链接至目标">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if all cased characters <a class="footnote-reference brackets" href="#id15" id="id7">4</a> in the string are uppercase and
there is at least one cased character, <code class="docutils literal notranslate"><span class="pre">False</span></code> otherwise.</p>
</dd></dl>

<dl class="method">
<dt id="str.join">
<code class="sig-prename descclassname">str.</code><code class="sig-name descname">join</code><span class="sig-paren">(</span><em class="sig-param">iterable</em><span class="sig-paren">)</span><a class="headerlink" href="#str.join" title="永久链接至目标">¶</a></dt>
<dd><p>返回一个由 <em>iterable</em> 中的字符串拼接而成的字符串。 如果 <em>iterable</em> 中存在任何非字符串值包括 <a class="reference internal" href="#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> 对象则会引发 <a class="reference internal" href="exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>。 调用该方法的字符串将作为元素之间的分隔。</p>
</dd></dl>

<dl class="method">
<dt id="str.ljust">
<code class="sig-prename descclassname">str.</code><code class="sig-name descname">ljust</code><span class="sig-paren">(</span><em class="sig-param">width</em><span class="optional">[</span>, <em class="sig-param">fillchar</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#str.ljust" title="永久链接至目标">¶</a></dt>
<dd><p>返回长度为 <em>width</em> 的字符串，原字符串在其中靠左对齐。 使用指定的 <em>fillchar</em> 填充空位 (默认使用 ASCII 空格符)。 如果 <em>width</em> 小于等于 <code class="docutils literal notranslate"><span class="pre">len(s)</span></code> 则返回原字符串的副本。</p>
</dd></dl>

<dl class="method">
<dt id="str.lower">
<code class="sig-prename descclassname">str.</code><code class="sig-name descname">lower</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#str.lower" title="永久链接至目标">¶</a></dt>
<dd><p>返回原字符串的副本，其所有区分大小写的字符 <a class="footnote-reference brackets" href="#id15" id="id8">4</a> 均转换为小写。</p>
<p>所用转换小写算法的描述请参见 Unicode 标准的 3.13 节。</p>
</dd></dl>

<dl class="method">
<dt id="str.lstrip">
<code class="sig-prename descclassname">str.</code><code class="sig-name descname">lstrip</code><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param">chars</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#str.lstrip" title="永久链接至目标">¶</a></dt>
<dd><p>返回原字符串的副本，移除其中的前导字符。 <em>chars</em> 参数为指定要移除字符的字符串。 如果省略或为 <code class="docutils literal notranslate"><span class="pre">None</span></code>，则 <em>chars</em> 参数默认移除空格符。 实际上 <em>chars</em> 参数并非指定单个前缀；而是会移除参数值的所有组合:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;   spacious   &#39;</span><span class="o">.</span><span class="n">lstrip</span><span class="p">()</span>
<span class="go">&#39;spacious   &#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;www.example.com&#39;</span><span class="o">.</span><span class="n">lstrip</span><span class="p">(</span><span class="s1">&#39;cmowz.&#39;</span><span class="p">)</span>
<span class="go">&#39;example.com&#39;</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="str.maketrans">
<em class="property">static </em><code class="sig-prename descclassname">str.</code><code class="sig-name descname">maketrans</code><span class="sig-paren">(</span><em class="sig-param">x</em><span class="optional">[</span>, <em class="sig-param">y</em><span class="optional">[</span>, <em class="sig-param">z</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#str.maketrans" title="永久链接至目标">¶</a></dt>
<dd><p>此静态方法返回一个可供 <a class="reference internal" href="#str.translate" title="str.translate"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.translate()</span></code></a> 使用的转换对照表。</p>
<p>如果只有一个参数，则它必须是一个将 Unicode 码位序号（整数）或字符（长度为 1 的字符串）映射到 Unicode 码位序号、（任意长度的）字符串或 <code class="docutils literal notranslate"><span class="pre">None</span></code> 的字典。 字符键将会被转换为码位序号。</p>
<p>如果有两个参数，则它们必须是两个长度相等的字符串，并且在结果字典中，x 中每个字符将被映射到 y 中相同位置的字符。 如果有第三个参数，它必须是一个字符串，其中的字符将在结果中被映射到 <code class="docutils literal notranslate"><span class="pre">None</span></code>。</p>
</dd></dl>

<dl class="method">
<dt id="str.partition">
<code class="sig-prename descclassname">str.</code><code class="sig-name descname">partition</code><span class="sig-paren">(</span><em class="sig-param">sep</em><span class="sig-paren">)</span><a class="headerlink" href="#str.partition" title="永久链接至目标">¶</a></dt>
<dd><p>在 <em>sep</em> 首次出现的位置拆分字符串，返回一个 3 元组，其中包含分隔符之前的部分、分隔符本身，以及分隔符之后的部分。 如果分隔符未找到，则返回的 3 元组中包含字符本身以及两个空字符串。</p>
</dd></dl>

<dl class="method">
<dt id="str.replace">
<code class="sig-prename descclassname">str.</code><code class="sig-name descname">replace</code><span class="sig-paren">(</span><em class="sig-param">old</em>, <em class="sig-param">new</em><span class="optional">[</span>, <em class="sig-param">count</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#str.replace" title="永久链接至目标">¶</a></dt>
<dd><p>返回字符串的副本，其中出现的所有子字符串 <em>old</em> 都将被替换为 <em>new</em>。 如果给出了可选参数 <em>count</em>，则只替换前 <em>count</em> 次出现。</p>
</dd></dl>

<dl class="method">
<dt id="str.rfind">
<code class="sig-prename descclassname">str.</code><code class="sig-name descname">rfind</code><span class="sig-paren">(</span><em class="sig-param">sub</em><span class="optional">[</span>, <em class="sig-param">start</em><span class="optional">[</span>, <em class="sig-param">end</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#str.rfind" title="永久链接至目标">¶</a></dt>
<dd><p>返回子字符串 <em>sub</em> 在字符串内被找到的最大（最右）索引，这样 <em>sub</em> 将包含在 <code class="docutils literal notranslate"><span class="pre">s[start:end]</span></code> 当中。 可选参数 <em>start</em> 与 <em>end</em> 会被解读为切片表示法。 如果未找到则返回 <code class="docutils literal notranslate"><span class="pre">-1</span></code>。</p>
</dd></dl>

<dl class="method">
<dt id="str.rindex">
<code class="sig-prename descclassname">str.</code><code class="sig-name descname">rindex</code><span class="sig-paren">(</span><em class="sig-param">sub</em><span class="optional">[</span>, <em class="sig-param">start</em><span class="optional">[</span>, <em class="sig-param">end</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#str.rindex" title="永久链接至目标">¶</a></dt>
<dd><p>类似于 <a class="reference internal" href="#str.rfind" title="str.rfind"><code class="xref py py-meth docutils literal notranslate"><span class="pre">rfind()</span></code></a>，但在子字符串 <em>sub</em> 未找到时会引发 <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>。</p>
</dd></dl>

<dl class="method">
<dt id="str.rjust">
<code class="sig-prename descclassname">str.</code><code class="sig-name descname">rjust</code><span class="sig-paren">(</span><em class="sig-param">width</em><span class="optional">[</span>, <em class="sig-param">fillchar</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#str.rjust" title="永久链接至目标">¶</a></dt>
<dd><p>返回长度为 <em>width</em> 的字符串，原字符串在其中靠右对齐。 使用指定的 <em>fillchar</em> 填充空位 (默认使用 ASCII 空格符)。 如果 <em>width</em> 小于等于 <code class="docutils literal notranslate"><span class="pre">len(s)</span></code> 则返回原字符串的副本。</p>
</dd></dl>

<dl class="method">
<dt id="str.rpartition">
<code class="sig-prename descclassname">str.</code><code class="sig-name descname">rpartition</code><span class="sig-paren">(</span><em class="sig-param">sep</em><span class="sig-paren">)</span><a class="headerlink" href="#str.rpartition" title="永久链接至目标">¶</a></dt>
<dd><p>在 <em>sep</em> 最后一次出现的位置拆分字符串，返回一个 3 元组，其中包含分隔符之前的部分、分隔符本身，以及分隔符之后的部分。 如果分隔符未找到，则返回的 3 元组中包含两个空字符串以及字符串本身。</p>
</dd></dl>

<dl class="method">
<dt id="str.rsplit">
<code class="sig-prename descclassname">str.</code><code class="sig-name descname">rsplit</code><span class="sig-paren">(</span><em class="sig-param">sep=None</em>, <em class="sig-param">maxsplit=-1</em><span class="sig-paren">)</span><a class="headerlink" href="#str.rsplit" title="永久链接至目标">¶</a></dt>
<dd><p>返回一个由字符串内单词组成的列表，使用 <em>sep</em> 作为分隔字符串。 如果给出了 <em>maxsplit</em>，则最多进行 <em>maxsplit</em> 次拆分，从 <em>最右边</em> 开始。 如果 <em>sep</em> 未指定或为 <code class="docutils literal notranslate"><span class="pre">None</span></code>，任何空白字符串都会被作为分隔符。 除了从右边开始拆分，<a class="reference internal" href="#str.rsplit" title="str.rsplit"><code class="xref py py-meth docutils literal notranslate"><span class="pre">rsplit()</span></code></a> 的其他行为都类似于下文所述的 <a class="reference internal" href="#str.split" title="str.split"><code class="xref py py-meth docutils literal notranslate"><span class="pre">split()</span></code></a>。</p>
</dd></dl>

<dl class="method">
<dt id="str.rstrip">
<code class="sig-prename descclassname">str.</code><code class="sig-name descname">rstrip</code><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param">chars</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#str.rstrip" title="永久链接至目标">¶</a></dt>
<dd><p>返回原字符串的副本，移除其中的末尾字符。 <em>chars</em> 参数为指定要移除字符的字符串。 如果省略或为 <code class="docutils literal notranslate"><span class="pre">None</span></code>，则 <em>chars</em> 参数默认移除空格符。 实际上 <em>chars</em> 参数并非指定单个后缀；而是会移除参数值的所有组合:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;   spacious   &#39;</span><span class="o">.</span><span class="n">rstrip</span><span class="p">()</span>
<span class="go">&#39;   spacious&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;mississippi&#39;</span><span class="o">.</span><span class="n">rstrip</span><span class="p">(</span><span class="s1">&#39;ipz&#39;</span><span class="p">)</span>
<span class="go">&#39;mississ&#39;</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="str.split">
<code class="sig-prename descclassname">str.</code><code class="sig-name descname">split</code><span class="sig-paren">(</span><em class="sig-param">sep=None</em>, <em class="sig-param">maxsplit=-1</em><span class="sig-paren">)</span><a class="headerlink" href="#str.split" title="永久链接至目标">¶</a></dt>
<dd><p>返回一个由字符串内单词组成的列表，使用 <em>sep</em> 作为分隔字符串。 如果给出了 <em>maxsplit</em>，则最多进行 <em>maxsplit</em> 次拆分（因此，列表最多会有 <code class="docutils literal notranslate"><span class="pre">maxsplit+1</span></code> 个元素）。 如果 <em>maxsplit</em> 未指定或为 <code class="docutils literal notranslate"><span class="pre">-1</span></code>，则不限制拆分次数（进行所有可能的拆分）。</p>
<p>如果给出了 <em>sep</em>，则连续的分隔符不会被组合在一起而是被视为分隔空字符串 (例如 <code class="docutils literal notranslate"><span class="pre">'1,,2'.split(',')</span></code> 将返回 <code class="docutils literal notranslate"><span class="pre">['1',</span> <span class="pre">'',</span> <span class="pre">'2']</span></code>)。 <em>sep</em> 参数可能由多个字符组成 (例如 <code class="docutils literal notranslate"><span class="pre">'1&lt;&gt;2&lt;&gt;3'.split('&lt;&gt;')</span></code> 将返回 <code class="docutils literal notranslate"><span class="pre">['1',</span> <span class="pre">'2',</span> <span class="pre">'3']</span></code>)。 使用指定的分隔符拆分空字符串将返回 <code class="docutils literal notranslate"><span class="pre">['']</span></code>。</p>
<p>例如</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;1,2,3&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s1">&#39;,&#39;</span><span class="p">)</span>
<span class="go">[&#39;1&#39;, &#39;2&#39;, &#39;3&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;1,2,3&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s1">&#39;,&#39;</span><span class="p">,</span> <span class="n">maxsplit</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="go">[&#39;1&#39;, &#39;2,3&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;1,2,,3,&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s1">&#39;,&#39;</span><span class="p">)</span>
<span class="go">[&#39;1&#39;, &#39;2&#39;, &#39;&#39;, &#39;3&#39;, &#39;&#39;]</span>
</pre></div>
</div>
<p>如果 <em>sep</em> 未指定或为 <code class="docutils literal notranslate"><span class="pre">None</span></code>，则会应用另一种拆分算法：连续的空格会被视为单个分隔符，其结果将不包含开头或末尾的空字符串，如果字符串包含前缀或后缀空格的话。 因此，使用 <code class="docutils literal notranslate"><span class="pre">None</span></code> 拆分空字符串或仅包含空格的字符串将返回 <code class="docutils literal notranslate"><span class="pre">[]</span></code>。</p>
<p>例如</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;1 2 3&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">()</span>
<span class="go">[&#39;1&#39;, &#39;2&#39;, &#39;3&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;1 2 3&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="n">maxsplit</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="go">[&#39;1&#39;, &#39;2 3&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;   1   2   3   &#39;</span><span class="o">.</span><span class="n">split</span><span class="p">()</span>
<span class="go">[&#39;1&#39;, &#39;2&#39;, &#39;3&#39;]</span>
</pre></div>
</div>
</dd></dl>

<span class="target" id="index-32"></span><dl class="method">
<dt id="str.splitlines">
<code class="sig-prename descclassname">str.</code><code class="sig-name descname">splitlines</code><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param">keepends</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#str.splitlines" title="永久链接至目标">¶</a></dt>
<dd><p>返回由原字符串中各行组成的列表，在行边界的位置拆分。 结果列表中不包含行边界，除非给出了 <em>keepends</em> 且为真值。</p>
<p>此方法会以下列行边界进行拆分。 特别地，行边界是 <a class="reference internal" href="../glossary.html#term-universal-newlines"><span class="xref std std-term">universal newlines</span></a> 的一个超集。</p>
<table class="docutils align-default">
<colgroup>
<col style="width: 44%" />
<col style="width: 56%" />
</colgroup>
<thead>
<tr class="row-odd"><th class="head"><p>表示符</p></th>
<th class="head"><p>描述</p></th>
</tr>
</thead>
<tbody>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">\n</span></code></p></td>
<td><p>换行</p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">\r</span></code></p></td>
<td><p>回车</p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">\r\n</span></code></p></td>
<td><p>回车 + 换行</p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">\v</span></code> 或 <code class="docutils literal notranslate"><span class="pre">\x0b</span></code></p></td>
<td><p>行制表符</p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">\f</span></code> 或 <code class="docutils literal notranslate"><span class="pre">\x0c</span></code></p></td>
<td><p>换表单</p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">\x1c</span></code></p></td>
<td><p>文件分隔符</p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">\x1d</span></code></p></td>
<td><p>组分隔符</p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">\x1e</span></code></p></td>
<td><p>记录分隔符</p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">\x85</span></code></p></td>
<td><p>下一行 (C1 控制码)</p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">\u2028</span></code></p></td>
<td><p>行分隔符</p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">\u2029</span></code></p></td>
<td><p>段分隔符</p></td>
</tr>
</tbody>
</table>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.2 版更改: </span><code class="docutils literal notranslate"><span class="pre">\v</span></code> 和 <code class="docutils literal notranslate"><span class="pre">\f</span></code> 被添加到行边界列表</p>
</div>
<p>例如</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;ab c</span><span class="se">\n\n</span><span class="s1">de fg</span><span class="se">\r</span><span class="s1">kl</span><span class="se">\r\n</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">splitlines</span><span class="p">()</span>
<span class="go">[&#39;ab c&#39;, &#39;&#39;, &#39;de fg&#39;, &#39;kl&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;ab c</span><span class="se">\n\n</span><span class="s1">de fg</span><span class="se">\r</span><span class="s1">kl</span><span class="se">\r\n</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">splitlines</span><span class="p">(</span><span class="n">keepends</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="go">[&#39;ab c\n&#39;, &#39;\n&#39;, &#39;de fg\r&#39;, &#39;kl\r\n&#39;]</span>
</pre></div>
</div>
<p>不同于 <a class="reference internal" href="#str.split" title="str.split"><code class="xref py py-meth docutils literal notranslate"><span class="pre">split()</span></code></a>，当给出了分隔字符串 <em>sep</em> 时，对于空字符串此方法将返回一个空列表，而末尾的换行不会令结果中增加额外的行:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s2">&quot;&quot;</span><span class="o">.</span><span class="n">splitlines</span><span class="p">()</span>
<span class="go">[]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s2">&quot;One line</span><span class="se">\n</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">splitlines</span><span class="p">()</span>
<span class="go">[&#39;One line&#39;]</span>
</pre></div>
</div>
<p>作为比较，<code class="docutils literal notranslate"><span class="pre">split('\n')</span></code> 的结果为:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s1">&#39;</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">)</span>
<span class="go">[&#39;&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;Two lines</span><span class="se">\n</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s1">&#39;</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">)</span>
<span class="go">[&#39;Two lines&#39;, &#39;&#39;]</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="str.startswith">
<code class="sig-prename descclassname">str.</code><code class="sig-name descname">startswith</code><span class="sig-paren">(</span><em class="sig-param">prefix</em><span class="optional">[</span>, <em class="sig-param">start</em><span class="optional">[</span>, <em class="sig-param">end</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#str.startswith" title="永久链接至目标">¶</a></dt>
<dd><p>如果字符串以指定的 <em>prefix</em> 开始则返回 <code class="docutils literal notranslate"><span class="pre">True</span></code>，否则返回 <code class="docutils literal notranslate"><span class="pre">False</span></code>。 <em>prefix</em> 也可以为由多个供查找的前缀构成的元组。 如果有可选项 <em>start</em>，将从所指定位置开始检查。 如果有可选项 <em>end</em>，将在所指定位置停止比较。</p>
</dd></dl>

<dl class="method">
<dt id="str.strip">
<code class="sig-prename descclassname">str.</code><code class="sig-name descname">strip</code><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param">chars</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#str.strip" title="永久链接至目标">¶</a></dt>
<dd><p>返回原字符串的副本，移除其中的前导和末尾字符。 <em>chars</em> 参数为指定要移除字符的字符串。 如果省略或为 <code class="docutils literal notranslate"><span class="pre">None</span></code>，则 <em>chars</em> 参数默认移除空格符。 实际上 <em>chars</em> 参数并非指定单个前缀或后缀；而是会移除参数值的所有组合:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;   spacious   &#39;</span><span class="o">.</span><span class="n">strip</span><span class="p">()</span>
<span class="go">&#39;spacious&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;www.example.com&#39;</span><span class="o">.</span><span class="n">strip</span><span class="p">(</span><span class="s1">&#39;cmowz.&#39;</span><span class="p">)</span>
<span class="go">&#39;example&#39;</span>
</pre></div>
</div>
<p>最外侧的前导和末尾 <em>chars</em> 参数值将从字符串中移除。 开头端的字符的移除将在遇到一个未包含于 <em>chars</em> 所指定字符集的字符时停止。 类似的操作也将在结尾端发生。 例如:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">comment_string</span> <span class="o">=</span> <span class="s1">&#39;#....... Section 3.2.1 Issue #32 .......&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">comment_string</span><span class="o">.</span><span class="n">strip</span><span class="p">(</span><span class="s1">&#39;.#! &#39;</span><span class="p">)</span>
<span class="go">&#39;Section 3.2.1 Issue #32&#39;</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="str.swapcase">
<code class="sig-prename descclassname">str.</code><code class="sig-name descname">swapcase</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#str.swapcase" title="永久链接至目标">¶</a></dt>
<dd><p>返回原字符串的副本，其中大写字符转换为小写，反之亦然。 请注意 <code class="docutils literal notranslate"><span class="pre">s.swapcase().swapcase()</span> <span class="pre">==</span> <span class="pre">s</span></code> 并不一定为真值。</p>
</dd></dl>

<dl class="method">
<dt id="str.title">
<code class="sig-prename descclassname">str.</code><code class="sig-name descname">title</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#str.title" title="永久链接至目标">¶</a></dt>
<dd><p>返回原字符串的标题版本，其中每个单词第一个字母为大写，其余字母为小写。</p>
<p>例如</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;Hello world&#39;</span><span class="o">.</span><span class="n">title</span><span class="p">()</span>
<span class="go">&#39;Hello World&#39;</span>
</pre></div>
</div>
<p>该算法使用一种简单的与语言无关的定义，将连续的字母组合视为单词。 该定义在多数情况下都很有效，但它也意味着代表缩写形式与所有格的撇号也会成为单词边界，这可能导致不希望的结果:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s2">&quot;they&#39;re bill&#39;s friends from the UK&quot;</span><span class="o">.</span><span class="n">title</span><span class="p">()</span>
<span class="go">&quot;They&#39;Re Bill&#39;S Friends From The Uk&quot;</span>
</pre></div>
</div>
<p>可以使用正则表达式来构建针对撇号的特别处理:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">re</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">titlecase</span><span class="p">(</span><span class="n">s</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">return</span> <span class="n">re</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="sa">r</span><span class="s2">&quot;[A-Za-z]+(&#39;[A-Za-z]+)?&quot;</span><span class="p">,</span>
<span class="gp">... </span>                  <span class="k">lambda</span> <span class="n">mo</span><span class="p">:</span> <span class="n">mo</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">0</span><span class="p">)[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">upper</span><span class="p">()</span> <span class="o">+</span>
<span class="gp">... </span>                             <span class="n">mo</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">0</span><span class="p">)[</span><span class="mi">1</span><span class="p">:]</span><span class="o">.</span><span class="n">lower</span><span class="p">(),</span>
<span class="gp">... </span>                  <span class="n">s</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">titlecase</span><span class="p">(</span><span class="s2">&quot;they&#39;re bill&#39;s friends.&quot;</span><span class="p">)</span>
<span class="go">&quot;They&#39;re Bill&#39;s Friends.&quot;</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="str.translate">
<code class="sig-prename descclassname">str.</code><code class="sig-name descname">translate</code><span class="sig-paren">(</span><em class="sig-param">table</em><span class="sig-paren">)</span><a class="headerlink" href="#str.translate" title="永久链接至目标">¶</a></dt>
<dd><p>返回原字符串的副本，其中每个字符按给定的转换表进行映射。 转换表必须是一个使用 <a class="reference internal" href="../reference/datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> 来实现索引操作的对象，通常为 <a class="reference internal" href="../glossary.html#term-mapping"><span class="xref std std-term">mapping</span></a> 或 <a class="reference internal" href="../glossary.html#term-sequence"><span class="xref std std-term">sequence</span></a>。 当以 Unicode 码位序号（整数）为索引时，转换表对象可以做以下任何一种操作：返回 Unicode 序号或字符串，将字符映射为一个或多个字符；返回 <code class="docutils literal notranslate"><span class="pre">None</span></code>，将字符从结果字符串中删除；或引发 <a class="reference internal" href="exceptions.html#LookupError" title="LookupError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">LookupError</span></code></a> 异常，将字符映射为其自身。</p>
<p>你可以使用 <a class="reference internal" href="#str.maketrans" title="str.maketrans"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.maketrans()</span></code></a> 基于不同格式的字符到字符映射来创建一个转换映射表。</p>
<p>另请参阅 <a class="reference internal" href="codecs.html#module-codecs" title="codecs: Encode and decode data and streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">codecs</span></code></a> 模块以了解定制字符映射的更灵活方式。</p>
</dd></dl>

<dl class="method">
<dt id="str.upper">
<code class="sig-prename descclassname">str.</code><code class="sig-name descname">upper</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#str.upper" title="永久链接至目标">¶</a></dt>
<dd><p>返回原字符串的副本，其中所有区分大小写的字符 <a class="footnote-reference brackets" href="#id15" id="id9">4</a> 均转换为大写。 请注意如果 <code class="docutils literal notranslate"><span class="pre">s</span></code> 包含不区分大小写的字符或者如果结果字符的 Unicode 类别不是 &quot;Lu&quot; (Letter, uppercase) 而是 &quot;Lt&quot; (Letter, titlecase) 则 <code class="docutils literal notranslate"><span class="pre">s.upper().isupper()</span></code> 有可能为 <code class="docutils literal notranslate"><span class="pre">False</span></code>。</p>
<p>所用转换大写算法的描述请参见 Unicode 标准的 3.13 节。</p>
</dd></dl>

<dl class="method">
<dt id="str.zfill">
<code class="sig-prename descclassname">str.</code><code class="sig-name descname">zfill</code><span class="sig-paren">(</span><em class="sig-param">width</em><span class="sig-paren">)</span><a class="headerlink" href="#str.zfill" title="永久链接至目标">¶</a></dt>
<dd><p>返回原字符串的副本，在左边填充 ASCII <code class="docutils literal notranslate"><span class="pre">'0'</span></code> 数码使其长度变为 <em>width</em>。 正负值前缀 (<code class="docutils literal notranslate"><span class="pre">'+'</span></code>/<code class="docutils literal notranslate"><span class="pre">'-'</span></code>) 的处理方式是在正负符号 <em>之后</em> 填充而非在之前。 如果 <em>width</em> 小于等于 <code class="docutils literal notranslate"><span class="pre">len(s)</span></code> 则返回原字符串的副本。</p>
<p>例如</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s2">&quot;42&quot;</span><span class="o">.</span><span class="n">zfill</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span>
<span class="go">&#39;00042&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s2">&quot;-42&quot;</span><span class="o">.</span><span class="n">zfill</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span>
<span class="go">&#39;-0042&#39;</span>
</pre></div>
</div>
</dd></dl>

</div>
<div class="section" id="printf-style-string-formatting">
<span id="old-string-formatting"></span><h3><code class="docutils literal notranslate"><span class="pre">printf</span></code> 风格的字符串格式化<a class="headerlink" href="#printf-style-string-formatting" title="永久链接至标题">¶</a></h3>
<div class="admonition note" id="index-33">
<p class="admonition-title">注解</p>
<p>此处介绍的格式化操作具有多种怪异特性，可能导致许多常见错误（例如无法正确显示元组和字典）。 使用较新的 <a class="reference internal" href="../reference/lexical_analysis.html#f-strings"><span class="std std-ref">格式化字符串字面值</span></a>，<a class="reference internal" href="#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.format()</span></code></a> 接口或 <a class="reference internal" href="string.html#template-strings"><span class="std std-ref">模板字符串</span></a> 有助于避免这样的错误。 这些替代方案中的每一种都更好地权衡并提供了简单、灵活以及可扩展性优势。</p>
</div>
<p>字符串具有一种特殊的内置操作：使用 <code class="docutils literal notranslate"><span class="pre">%</span></code> (取模) 运算符。 这也被称为字符串的 <em>格式化</em> 或 <em>插值</em> 运算符。 对于 <code class="docutils literal notranslate"><span class="pre">format</span> <span class="pre">%</span> <span class="pre">values</span></code> (其中 <em>format</em> 为一个字符串)，在 <em>format</em> 中的 <code class="docutils literal notranslate"><span class="pre">%</span></code> 转换标记符将被替换为零个或多个 <em>values</em> 条目。 其效果类似于在 C 语言中使用 <code class="xref c c-func docutils literal notranslate"><span class="pre">sprintf()</span></code>。</p>
<p>如果 <em>format</em> 要求一个单独参数，则 <em>values</em> 可以为一个非元组对象。 <a class="footnote-reference brackets" href="#id16" id="id10">5</a>  否则的话，<em>values</em> 必须或者是一个包含项数与格式字符串中指定的转换符项数相同的元组，或者是一个单独映射对象（例如字典）。</p>
<p id="index-34">转换标记符包含两个或更多字符并具有以下组成，且必须遵循此处规定的顺序：</p>
<ol class="arabic simple">
<li><p><code class="docutils literal notranslate"><span class="pre">'%'</span></code> 字符，用于标记转换符的起始。</p></li>
<li><p>映射键（可选），由加圆括号的字符序列组成 (例如 <code class="docutils literal notranslate"><span class="pre">(somename)</span></code>)。</p></li>
<li><p>转换旗标（可选），用于影响某些转换类型的结果。</p></li>
<li><p>最小字段宽度（可选）。 如果指定为 <code class="docutils literal notranslate"><span class="pre">'*'</span></code> (星号)，则实际宽度会从 <em>values</em> 元组的下一元素中读取，要转换的对象则为最小字段宽度和可选的精度之后的元素。</p></li>
<li><p>精度（可选），以在 <code class="docutils literal notranslate"><span class="pre">'.'</span></code> (点号) 之后加精度值的形式给出。 如果指定为 <code class="docutils literal notranslate"><span class="pre">'*'</span></code> (星号)，则实际精度会从 <em>values</em> 元组的下一元素中读取，要转换的对象则为精度之后的元素。</p></li>
<li><p>长度修饰符（可选）。</p></li>
<li><p>转换类型。</p></li>
</ol>
<p>当右边的参数为一个字典（或其他映射类型）时，字符串中的格式 <em>必须</em> 包含加圆括号的映射键，对应 <code class="docutils literal notranslate"><span class="pre">'%'</span></code> 字符之后字典中的每一项。 映射键将从映射中选取要格式化的值。 例如：</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="s1">&#39;</span><span class="si">%(language)s</span><span class="s1"> has </span><span class="si">%(number)03d</span><span class="s1"> quote types.&#39;</span> <span class="o">%</span>
<span class="gp">... </span>      <span class="p">{</span><span class="s1">&#39;language&#39;</span><span class="p">:</span> <span class="s2">&quot;Python&quot;</span><span class="p">,</span> <span class="s2">&quot;number&quot;</span><span class="p">:</span> <span class="mi">2</span><span class="p">})</span>
<span class="go">Python has 002 quote types.</span>
</pre></div>
</div>
<p>在此情况下格式中不能出现 <code class="docutils literal notranslate"><span class="pre">*</span></code> 标记符（因其需要一个序列类的参数列表）。</p>
<p>转换旗标为：</p>
<table class="docutils align-default" id="index-35">
<colgroup>
<col style="width: 12%" />
<col style="width: 88%" />
</colgroup>
<thead>
<tr class="row-odd"><th class="head"><p>标志</p></th>
<th class="head"><p>含义</p></th>
</tr>
</thead>
<tbody>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">'#'</span></code></p></td>
<td><p>值的转换将使用“替代形式”（具体定义见下文）。</p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">'0'</span></code></p></td>
<td><p>转换将为数字值填充零字符。</p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">'-'</span></code></p></td>
<td><p>转换值将靠左对齐（如果同时给出 <code class="docutils literal notranslate"><span class="pre">'0'</span></code> 转换，则会覆盖后者）。</p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">'</span> <span class="pre">'</span></code></p></td>
<td><p>(空格) 符号位转换产生的正数（或空字符串）前将留出一个空格。</p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">'+'</span></code></p></td>
<td><p>符号字符 (<code class="docutils literal notranslate"><span class="pre">'+'</span></code> 或 <code class="docutils literal notranslate"><span class="pre">'-'</span></code>) 将显示于转换结果的开头（会覆盖 &quot;空格&quot; 旗标）。</p></td>
</tr>
</tbody>
</table>
<p>可以给出长度修饰符 (<code class="docutils literal notranslate"><span class="pre">h</span></code>, <code class="docutils literal notranslate"><span class="pre">l</span></code> 或 <code class="docutils literal notranslate"><span class="pre">L</span></code>)，但会被忽略，因为对 Python 来说没有必要 -- 所以 <code class="docutils literal notranslate"><span class="pre">%ld</span></code> 等价于 <code class="docutils literal notranslate"><span class="pre">%d</span></code>。</p>
<p>转换类型为：</p>
<table class="docutils align-default">
<colgroup>
<col style="width: 17%" />
<col style="width: 74%" />
<col style="width: 10%" />
</colgroup>
<thead>
<tr class="row-odd"><th class="head"><p>转换符</p></th>
<th class="head"><p>含义</p></th>
<th class="head"><p>注释</p></th>
</tr>
</thead>
<tbody>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">'d'</span></code></p></td>
<td><p>有符号十进制整数。</p></td>
<td></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">'i'</span></code></p></td>
<td><p>有符号十进制整数。</p></td>
<td></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">'o'</span></code></p></td>
<td><p>有符号八进制数。</p></td>
<td><p>(1)</p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">'u'</span></code></p></td>
<td><p>过时类型 -- 等价于 <code class="docutils literal notranslate"><span class="pre">'d'</span></code>。</p></td>
<td><p>(6)</p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">'x'</span></code></p></td>
<td><p>有符号十六进制数（小写）。</p></td>
<td><p>(2)</p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">'X'</span></code></p></td>
<td><p>有符号十六进制数（大写）。</p></td>
<td><p>(2)</p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">'e'</span></code></p></td>
<td><p>浮点指数格式（小写）。</p></td>
<td><p>(3)</p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">'E'</span></code></p></td>
<td><p>浮点指数格式（大写）。</p></td>
<td><p>(3)</p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">'f'</span></code></p></td>
<td><p>浮点十进制格式。</p></td>
<td><p>(3)</p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">'F'</span></code></p></td>
<td><p>浮点十进制格式。</p></td>
<td><p>(3)</p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">'g'</span></code></p></td>
<td><p>浮点格式。 如果指数小于 -4 或不小于精度则使用小写指数格式，否则使用十进制格式。</p></td>
<td><p>(4)</p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">'G'</span></code></p></td>
<td><p>浮点格式。 如果指数小于 -4 或不小于精度则使用大写指数格式，否则使用十进制格式。</p></td>
<td><p>(4)</p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">'c'</span></code></p></td>
<td><p>单个字符（接受整数或单个字符的字符串）。</p></td>
<td></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">'r'</span></code></p></td>
<td><p>字符串（使用 <a class="reference internal" href="functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a> 转换任何 Python 对象）。</p></td>
<td><p>(5)</p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">'s'</span></code></p></td>
<td><p>字符串（使用 <a class="reference internal" href="#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> 转换任何 Python 对象）。</p></td>
<td><p>(5)</p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">'a'</span></code></p></td>
<td><p>字符串（使用 <a class="reference internal" href="functions.html#ascii" title="ascii"><code class="xref py py-func docutils literal notranslate"><span class="pre">ascii()</span></code></a> 转换任何 Python 对象）。</p></td>
<td><p>(5)</p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">'%'</span></code></p></td>
<td><p>不转换参数，在结果中输出一个 <code class="docutils literal notranslate"><span class="pre">'%'</span></code> 字符。</p></td>
<td></td>
</tr>
</tbody>
</table>
<p>注释:</p>
<ol class="arabic">
<li><p>此替代形式会在第一个数码之前插入标示八进制数的前缀 (<code class="docutils literal notranslate"><span class="pre">'0o'</span></code>)。</p></li>
<li><p>此替代形式会在第一个数码之前插入 <code class="docutils literal notranslate"><span class="pre">'0x'</span></code> 或 <code class="docutils literal notranslate"><span class="pre">'0X'</span></code> 前缀（取决于是使用 <code class="docutils literal notranslate"><span class="pre">'x'</span></code> 还是 <code class="docutils literal notranslate"><span class="pre">'X'</span></code> 格式）。</p></li>
<li><p>此替代形式总是会在结果中包含一个小数点，即使其后并没有数码。</p>
<p>小数点后的数码位数由精度决定，默认为 6。</p>
</li>
<li><p>此替代形式总是会在结果中包含一个小数点，末尾各位的零不会如其他情况下那样被移除。</p>
<p>小数点前后的有效数码位数由精度决定，默认为 6。</p>
</li>
<li><p>如果精度为 <code class="docutils literal notranslate"><span class="pre">N</span></code>，输出将截短为 <code class="docutils literal notranslate"><span class="pre">N</span></code> 个字符。</p></li>
<li><p>参见 <span class="target" id="index-64"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0237"><strong>PEP 237</strong></a>。</p></li>
</ol>
<p>由于 Python 字符串显式指明长度，<code class="docutils literal notranslate"><span class="pre">%s</span></code> 转换不会将 <code class="docutils literal notranslate"><span class="pre">'\0'</span></code> 视为字符串的结束。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.1 版更改: </span>绝对值超过 1e50 的 <code class="docutils literal notranslate"><span class="pre">%f</span></code> 转换不会再被替换为 <code class="docutils literal notranslate"><span class="pre">%g</span></code> 转换。</p>
</div>
</div>
</div>
<div class="section" id="binary-sequence-types-bytes-bytearray-memoryview">
<span id="binaryseq"></span><span id="index-37"></span><h2>二进制序列类型 --- <a class="reference internal" href="#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a>, <a class="reference internal" href="#bytearray" title="bytearray"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytearray</span></code></a>, <a class="reference internal" href="#memoryview" title="memoryview"><code class="xref py py-class docutils literal notranslate"><span class="pre">memoryview</span></code></a><a class="headerlink" href="#binary-sequence-types-bytes-bytearray-memoryview" title="永久链接至标题">¶</a></h2>
<p id="index-38">操作二进制数据的核心内置类型是 <a class="reference internal" href="#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> 和 <a class="reference internal" href="#bytearray" title="bytearray"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytearray</span></code></a>。 它们由 <a class="reference internal" href="#memoryview" title="memoryview"><code class="xref py py-class docutils literal notranslate"><span class="pre">memoryview</span></code></a> 提供支持，该对象使用 <a class="reference internal" href="../c-api/buffer.html#bufferobjects"><span class="std std-ref">缓冲区协议</span></a> 来访问其他二进制对象所在内存，不需要创建对象的副本。</p>
<p><a class="reference internal" href="array.html#module-array" title="array: Space efficient arrays of uniformly typed numeric values."><code class="xref py py-mod docutils literal notranslate"><span class="pre">array</span></code></a> 模块支持高效地存储基本数据类型，例如 32 位整数和 IEEE754 双精度浮点值。</p>
<div class="section" id="bytes-objects">
<span id="typebytes"></span><h3>bytes 对象<a class="headerlink" href="#bytes-objects" title="永久链接至标题">¶</a></h3>
<p id="index-39">bytes 对象是由单个字节构成的不可变序列。 由于许多主要二进制协议都基于 ASCII 文本编码，因此 bytes 对象提供了一些仅在处理 ASCII 兼容数据时可用，并且在许多特性上与字符串对象紧密相关的方法。</p>
<dl class="class">
<dt id="bytes">
<em class="property">class </em><code class="sig-name descname">bytes</code><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param">source</em><span class="optional">[</span>, <em class="sig-param">encoding</em><span class="optional">[</span>, <em class="sig-param">errors</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#bytes" title="永久链接至目标">¶</a></dt>
<dd><p>首先，表示 bytes 字面值的语法与字符串字面值的大致相同，只是添加了一个 <code class="docutils literal notranslate"><span class="pre">b</span></code> 前缀：</p>
<ul class="simple">
<li><p>单引号: <code class="docutils literal notranslate"><span class="pre">b'同样允许嵌入</span> <span class="pre">&quot;双&quot;</span> <span class="pre">引号'</span></code>。</p></li>
<li><p>双引号: <code class="docutils literal notranslate"><span class="pre">b&quot;同样允许嵌入</span> <span class="pre">'单'</span> <span class="pre">引号&quot;</span></code>。</p></li>
<li><p>三重引号: <code class="docutils literal notranslate"><span class="pre">b'''三重单引号'''</span></code>, <code class="docutils literal notranslate"><span class="pre">b&quot;&quot;&quot;三重双引号&quot;&quot;&quot;</span></code></p></li>
</ul>
<p>bytes 字面值中只允许 ASCII 字符（无论源代码声明的编码为何）。 任何超出 127 的二进制值必须使用相应的转义序列形式加入 bytes 字面值。</p>
<p>像字符串字面值一样，bytes 字面值也可以使用 <code class="docutils literal notranslate"><span class="pre">r</span></code> 前缀来禁用转义序列处理。 请参阅 <a class="reference internal" href="../reference/lexical_analysis.html#strings"><span class="std std-ref">字符串和字节串字面值</span></a> 了解有关各种 bytes 字面值形式的详情，包括所支持的转义序列。</p>
<p>虽然 bytes 字面值和表示法是基于 ASCII 文本的，但 bytes 对象的行为实际上更像是不可变的整数序列，序列中的每个值的大小被限制为 <code class="docutils literal notranslate"><span class="pre">0</span> <span class="pre">&lt;=</span> <span class="pre">x</span> <span class="pre">&lt;</span> <span class="pre">256</span></code> (如果违反此限制将引发 <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>)。 这种限制是有意设计用以强调以下事实，虽然许多二进制格式都包含基于 ASCII 的元素，可以通过某些面向文本的算法进行有用的操作，但情况对于任意二进制数据来说通常却并非如此（盲目地将文本处理算法应用于不兼容 ASCII 的二进制数据格式往往将导致数据损坏）。</p>
<p>除了字面值形式，bytes 对象还可以通过其他几种方式来创建：</p>
<ul class="simple">
<li><p>指定长度的以零值填充的 bytes 对象: <code class="docutils literal notranslate"><span class="pre">bytes(10)</span></code></p></li>
<li><p>通过由整数组成的可迭代对象: <code class="docutils literal notranslate"><span class="pre">bytes(range(20))</span></code></p></li>
<li><p>通过缓冲区协议复制现有的二进制数据:  <code class="docutils literal notranslate"><span class="pre">bytes(obj)</span></code></p></li>
</ul>
<p>另请参阅 <a class="reference internal" href="functions.html#func-bytes"><span class="std std-ref">bytes</span></a> 内置类型。</p>
<p>由于两个十六进制数码精确对应一个字节，因此十六进制数是描述二进制数据的常用格式。 相应地，bytes 类型具有从此种格式读取数据的附加类方法：</p>
<dl class="method">
<dt id="bytes.fromhex">
<em class="property">classmethod </em><code class="sig-name descname">fromhex</code><span class="sig-paren">(</span><em class="sig-param">string</em><span class="sig-paren">)</span><a class="headerlink" href="#bytes.fromhex" title="永久链接至目标">¶</a></dt>
<dd><p>此 <a class="reference internal" href="#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> 类方法返回一个解码给定字符串的 bytes 对象。 字符串必须由表示每个字节的两个十六进制数码构成，其中的 ASCII 空白符会被忽略。</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">bytes</span><span class="o">.</span><span class="n">fromhex</span><span class="p">(</span><span class="s1">&#39;2Ef0 F1f2  &#39;</span><span class="p">)</span>
<span class="go">b&#39;.\xf0\xf1\xf2&#39;</span>
</pre></div>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.7 版更改: </span><a class="reference internal" href="#bytes.fromhex" title="bytes.fromhex"><code class="xref py py-meth docutils literal notranslate"><span class="pre">bytes.fromhex()</span></code></a> 现在会忽略所有 ASCII 空白符而不只是空格符。</p>
</div>
</dd></dl>

<p>存在一个反向转换函数，可以将 bytes 对象转换为对应的十六进制表示。</p>
<dl class="method">
<dt id="bytes.hex">
<code class="sig-name descname">hex</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#bytes.hex" title="永久链接至目标">¶</a></dt>
<dd><p>返回一个字符串对象，该对象包含实例中每个字节的两个十六进制数字。</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="sa">b</span><span class="s1">&#39;</span><span class="se">\xf0\xf1\xf2</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">hex</span><span class="p">()</span>
<span class="go">&#39;f0f1f2&#39;</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified added">3.5 新版功能.</span></p>
</div>
</dd></dl>

</dd></dl>

<p>由于 bytes 对象是由整数构成的序列（类似于元组），因此对于一个 bytes 对象 <em>b</em>，<code class="docutils literal notranslate"><span class="pre">b[0]</span></code> 将为一个整数，而 <code class="docutils literal notranslate"><span class="pre">b[0:1]</span></code> 将为一个长度为 1 的 bytes 对象。 （这与文本字符串不同，索引和切片所产生的将都是一个长度为 1 的字符串）。</p>
<p>bytes 对象的表示使用字面值格式 (<code class="docutils literal notranslate"><span class="pre">b'...'</span></code>)，因为它通常都要比像 <code class="docutils literal notranslate"><span class="pre">bytes([46,</span> <span class="pre">46,</span> <span class="pre">46])</span></code> 这样的格式更好用。 你总是可以使用 <code class="docutils literal notranslate"><span class="pre">list(b)</span></code> 将 bytes 对象转换为一个由整数构成的列表。</p>
<div class="admonition note">
<p class="admonition-title">注解</p>
<p>针对 Python 2.x 用户的说明：在 Python 2.x 系列中，允许 8 位字符串（ 2.x 所提供的最接近内置二进制数据类型的对象）与 Unicode 字符串进行各种隐式转换。 这是为了实现向下兼容的变通做法，以适应 Python 最初只支持 8 位文本而 Unicode 文本是后来才被加入这一事实。 在 Python 3.x 中，这些隐式转换已被取消 —— 8 位二进制数据与 Unicode 文本间的转换必须显式地进行，bytes 与字符串对象的比较结果将总是不相等。</p>
</div>
</div>
<div class="section" id="bytearray-objects">
<span id="typebytearray"></span><h3>bytearray 对象<a class="headerlink" href="#bytearray-objects" title="永久链接至标题">¶</a></h3>
<p id="index-40"><a class="reference internal" href="#bytearray" title="bytearray"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytearray</span></code></a> 对象是 <a class="reference internal" href="#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> 对象的可变对应物。</p>
<dl class="class">
<dt id="bytearray">
<em class="property">class </em><code class="sig-name descname">bytearray</code><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param">source</em><span class="optional">[</span>, <em class="sig-param">encoding</em><span class="optional">[</span>, <em class="sig-param">errors</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#bytearray" title="永久链接至目标">¶</a></dt>
<dd><p>bytearray 对象没有专属的字面值语法，它们总是通过调用构造器来创建：</p>
<ul class="simple">
<li><p>创建一个空实例: <code class="docutils literal notranslate"><span class="pre">bytearray()</span></code></p></li>
<li><p>创建一个指定长度的以零值填充的实例: <code class="docutils literal notranslate"><span class="pre">bytearray(10)</span></code></p></li>
<li><p>通过由整数组成的可迭代对象: <code class="docutils literal notranslate"><span class="pre">bytearray(range(20))</span></code></p></li>
<li><p>通过缓冲区协议复制现有的二进制数据:  <code class="docutils literal notranslate"><span class="pre">bytearray(b'Hi!')</span></code></p></li>
</ul>
<p>由于 bytearray 对象是可变的，该对象除了 <a class="reference internal" href="#bytes-methods"><span class="std std-ref">bytes 和 bytearray 操作</span></a> 中所描述的 bytes 和 bytearray 共有操作之外，还支持 <a class="reference internal" href="#typesseq-mutable"><span class="std std-ref">可变</span></a> 序列操作。</p>
<p>另请参见 <a class="reference internal" href="functions.html#func-bytearray"><span class="std std-ref">bytearray</span></a> 内置类型。</p>
<p>由于两个十六进制数码精确对应一个字节，因此十六进制数是描述二进制数据的常用格式。 相应地，bytearray 类型具有从此种格式读取数据的附加类方法：</p>
<dl class="method">
<dt id="bytearray.fromhex">
<em class="property">classmethod </em><code class="sig-name descname">fromhex</code><span class="sig-paren">(</span><em class="sig-param">string</em><span class="sig-paren">)</span><a class="headerlink" href="#bytearray.fromhex" title="永久链接至目标">¶</a></dt>
<dd><p><a class="reference internal" href="#bytearray" title="bytearray"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytearray</span></code></a> 类方法返回一个解码给定字符串的 bytearray 对象。 字符串必须由表示每个字节的两个十六进制数码构成，其中的 ASCII 空白符会被忽略。</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">bytearray</span><span class="o">.</span><span class="n">fromhex</span><span class="p">(</span><span class="s1">&#39;2Ef0 F1f2  &#39;</span><span class="p">)</span>
<span class="go">bytearray(b&#39;.\xf0\xf1\xf2&#39;)</span>
</pre></div>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.7 版更改: </span><a class="reference internal" href="#bytearray.fromhex" title="bytearray.fromhex"><code class="xref py py-meth docutils literal notranslate"><span class="pre">bytearray.fromhex()</span></code></a> 现在会忽略所有 ASCII 空白符而不只是空格符。</p>
</div>
</dd></dl>

<p>存在一个反向转换函数，可以将 bytearray 对象转换为对应的十六进制表示。</p>
<dl class="method">
<dt id="bytearray.hex">
<code class="sig-name descname">hex</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#bytearray.hex" title="永久链接至目标">¶</a></dt>
<dd><p>返回一个字符串对象，该对象包含实例中每个字节的两个十六进制数字。</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">bytearray</span><span class="p">(</span><span class="sa">b</span><span class="s1">&#39;</span><span class="se">\xf0\xf1\xf2</span><span class="s1">&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">hex</span><span class="p">()</span>
<span class="go">&#39;f0f1f2&#39;</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified added">3.5 新版功能.</span></p>
</div>
</dd></dl>

</dd></dl>

<p>由于 bytearray 对象是由整数构成的序列（类似于列表），因此对于一个 bytearray 对象 <em>b</em>，<code class="docutils literal notranslate"><span class="pre">b[0]</span></code> 将为一个整数，而 <code class="docutils literal notranslate"><span class="pre">b[0:1]</span></code> 将为一个长度为 1 的 bytearray 对象。 （这与文本字符串不同，索引和切片所产生的将都是一个长度为 1 的字符串）。</p>
<p>bytearray 对象的表示使用 bytes 对象字面值格式 (<code class="docutils literal notranslate"><span class="pre">bytearray(b'...')</span></code>)，因为它通常都要比 <code class="docutils literal notranslate"><span class="pre">bytearray([46,</span> <span class="pre">46,</span> <span class="pre">46])</span></code> 这样的格式更好用。 你总是可以使用 <code class="docutils literal notranslate"><span class="pre">list(b)</span></code> 将 bytearray 对象转换为一个由整数构成的列表。</p>
</div>
<div class="section" id="bytes-and-bytearray-operations">
<span id="bytes-methods"></span><h3>bytes 和 bytearray 操作<a class="headerlink" href="#bytes-and-bytearray-operations" title="永久链接至标题">¶</a></h3>
<p id="index-41">bytes 和 bytearray 对象都支持 <a class="reference internal" href="#typesseq-common"><span class="std std-ref">通用</span></a> 序列操作。 它们不仅能与相同类型的操作数，也能与任何 <a class="reference internal" href="../glossary.html#term-bytes-like-object"><span class="xref std std-term">bytes-like object</span></a> 进行互操作。 由于这样的灵活性，它们可以在操作中自由地混合而不会导致错误。 但是，操作结果的返回值类型可能取决于操作数的顺序。</p>
<div class="admonition note">
<p class="admonition-title">注解</p>
<p>bytes 和 bytearray 对象的方法不接受字符串作为其参数，就像字符串的方法不接受 bytes 对象作为其参数一样。 例如，你必须使用以下写法:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">a</span> <span class="o">=</span> <span class="s2">&quot;abc&quot;</span>
<span class="n">b</span> <span class="o">=</span> <span class="n">a</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span><span class="s2">&quot;a&quot;</span><span class="p">,</span> <span class="s2">&quot;f&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>和:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">a</span> <span class="o">=</span> <span class="sa">b</span><span class="s2">&quot;abc&quot;</span>
<span class="n">b</span> <span class="o">=</span> <span class="n">a</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span><span class="sa">b</span><span class="s2">&quot;a&quot;</span><span class="p">,</span> <span class="sa">b</span><span class="s2">&quot;f&quot;</span><span class="p">)</span>
</pre></div>
</div>
</div>
<p>某些 bytes 和 bytearray 操作假定使用兼容 ASCII 的二进制格式，因此在处理任意二进数数据时应当避免使用。 这些限制会在下文中说明。</p>
<div class="admonition note">
<p class="admonition-title">注解</p>
<p>使用这些基于 ASCII 的操作来处理未以基于 ASCII 的格式存储的二进制数据可能会导致数据损坏。</p>
</div>
<p>bytes 和 bytearray 对象的下列方法可以用于任意二进制数据。</p>
<dl class="method">
<dt id="bytes.count">
<code class="sig-prename descclassname">bytes.</code><code class="sig-name descname">count</code><span class="sig-paren">(</span><em class="sig-param">sub</em><span class="optional">[</span>, <em class="sig-param">start</em><span class="optional">[</span>, <em class="sig-param">end</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#bytes.count" title="永久链接至目标">¶</a></dt>
<dt id="bytearray.count">
<code class="sig-prename descclassname">bytearray.</code><code class="sig-name descname">count</code><span class="sig-paren">(</span><em class="sig-param">sub</em><span class="optional">[</span>, <em class="sig-param">start</em><span class="optional">[</span>, <em class="sig-param">end</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#bytearray.count" title="永久链接至目标">¶</a></dt>
<dd><p>返回子序列 <em>sub</em> 在 [<em>start</em>, <em>end</em>] 范围内非重叠出现的次数。 可选参数 <em>start</em> 与 <em>end</em> 会被解读为切片表示法。</p>
<p>要搜索的子序列可以是任意 <a class="reference internal" href="../glossary.html#term-bytes-like-object"><span class="xref std std-term">bytes-like object</span></a> 或是 0 至 255 范围内的整数。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.3 版更改: </span>也接受 0 至 255 范围内的整数作为子序列。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="bytes.decode">
<code class="sig-prename descclassname">bytes.</code><code class="sig-name descname">decode</code><span class="sig-paren">(</span><em class="sig-param">encoding=&quot;utf-8&quot;</em>, <em class="sig-param">errors=&quot;strict&quot;</em><span class="sig-paren">)</span><a class="headerlink" href="#bytes.decode" title="永久链接至目标">¶</a></dt>
<dt id="bytearray.decode">
<code class="sig-prename descclassname">bytearray.</code><code class="sig-name descname">decode</code><span class="sig-paren">(</span><em class="sig-param">encoding=&quot;utf-8&quot;</em>, <em class="sig-param">errors=&quot;strict&quot;</em><span class="sig-paren">)</span><a class="headerlink" href="#bytearray.decode" title="永久链接至目标">¶</a></dt>
<dd><p>返回从给定 bytes 解码出来的字符串。 默认编码为 <code class="docutils literal notranslate"><span class="pre">'utf-8'</span></code>。 可以给出 <em>errors</em> 来设置不同的错误处理方案。 <em>errors</em> 的默认值为 <code class="docutils literal notranslate"><span class="pre">'strict'</span></code>，表示编码错误会引发 <a class="reference internal" href="exceptions.html#UnicodeError" title="UnicodeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeError</span></code></a>。 其他可用的值为 <code class="docutils literal notranslate"><span class="pre">'ignore'</span></code>, <code class="docutils literal notranslate"><span class="pre">'replace'</span></code> 以及任何其他通过 <a class="reference internal" href="codecs.html#codecs.register_error" title="codecs.register_error"><code class="xref py py-func docutils literal notranslate"><span class="pre">codecs.register_error()</span></code></a> 注册的名称，请参阅 <a class="reference internal" href="codecs.html#error-handlers"><span class="std std-ref">错误处理方案</span></a> 小节。 要查看可用的编码列表，请参阅 <a class="reference internal" href="codecs.html#standard-encodings"><span class="std std-ref">标准编码</span></a> 小节。</p>
<div class="admonition note">
<p class="admonition-title">注解</p>
<p>将 <em>encoding</em> 参数传给 <a class="reference internal" href="#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> 允许直接解码任何 <a class="reference internal" href="../glossary.html#term-bytes-like-object"><span class="xref std std-term">bytes-like object</span></a>，无须创建临时的 bytes 或 bytearray 对象。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.1 版更改: </span>加入了对关键字参数的支持。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="bytes.endswith">
<code class="sig-prename descclassname">bytes.</code><code class="sig-name descname">endswith</code><span class="sig-paren">(</span><em class="sig-param">suffix</em><span class="optional">[</span>, <em class="sig-param">start</em><span class="optional">[</span>, <em class="sig-param">end</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#bytes.endswith" title="永久链接至目标">¶</a></dt>
<dt id="bytearray.endswith">
<code class="sig-prename descclassname">bytearray.</code><code class="sig-name descname">endswith</code><span class="sig-paren">(</span><em class="sig-param">suffix</em><span class="optional">[</span>, <em class="sig-param">start</em><span class="optional">[</span>, <em class="sig-param">end</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#bytearray.endswith" title="永久链接至目标">¶</a></dt>
<dd><p>如果二进制数据以指定的 <em>suffix</em> 结束则返回 <code class="docutils literal notranslate"><span class="pre">True</span></code>，否则返回 <code class="docutils literal notranslate"><span class="pre">False</span></code>。 <em>suffix</em> 也可以为由多个供查找的后缀构成的元组。 如果有可选项 <em>start</em>，将从所指定位置开始检查。 如果有可选项 <em>end</em>，将在所指定位置停止比较。</p>
<p>要搜索的后缀可以是任意 <a class="reference internal" href="../glossary.html#term-bytes-like-object"><span class="xref std std-term">bytes-like object</span></a>。</p>
</dd></dl>

<dl class="method">
<dt id="bytes.find">
<code class="sig-prename descclassname">bytes.</code><code class="sig-name descname">find</code><span class="sig-paren">(</span><em class="sig-param">sub</em><span class="optional">[</span>, <em class="sig-param">start</em><span class="optional">[</span>, <em class="sig-param">end</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#bytes.find" title="永久链接至目标">¶</a></dt>
<dt id="bytearray.find">
<code class="sig-prename descclassname">bytearray.</code><code class="sig-name descname">find</code><span class="sig-paren">(</span><em class="sig-param">sub</em><span class="optional">[</span>, <em class="sig-param">start</em><span class="optional">[</span>, <em class="sig-param">end</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#bytearray.find" title="永久链接至目标">¶</a></dt>
<dd><p>返回子序列 <em>sub</em> 在数据中被找到的最小索引，<em>sub</em> 包含于切片 <code class="docutils literal notranslate"><span class="pre">s[start:end]</span></code> 之内。 可选参数 <em>start</em> 与 <em>end</em> 会被解读为切片表示法。 如果 <em>sub</em> 未被找到则返回 <code class="docutils literal notranslate"><span class="pre">-1</span></code>。</p>
<p>要搜索的子序列可以是任意 <a class="reference internal" href="../glossary.html#term-bytes-like-object"><span class="xref std std-term">bytes-like object</span></a> 或是 0 至 255 范围内的整数。</p>
<div class="admonition note">
<p class="admonition-title">注解</p>
<p><a class="reference internal" href="#bytes.find" title="bytes.find"><code class="xref py py-meth docutils literal notranslate"><span class="pre">find()</span></code></a> 方法应该只在你需要知道 <em>sub</em> 所在位置时使用。 要检查 <em>sub</em> 是否为子串，请使用 <a class="reference internal" href="../reference/expressions.html#in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code></a> 操作符:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="sa">b</span><span class="s1">&#39;Py&#39;</span> <span class="ow">in</span> <span class="sa">b</span><span class="s1">&#39;Python&#39;</span>
<span class="go">True</span>
</pre></div>
</div>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.3 版更改: </span>也接受 0 至 255 范围内的整数作为子序列。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="bytes.index">
<code class="sig-prename descclassname">bytes.</code><code class="sig-name descname">index</code><span class="sig-paren">(</span><em class="sig-param">sub</em><span class="optional">[</span>, <em class="sig-param">start</em><span class="optional">[</span>, <em class="sig-param">end</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#bytes.index" title="永久链接至目标">¶</a></dt>
<dt id="bytearray.index">
<code class="sig-prename descclassname">bytearray.</code><code class="sig-name descname">index</code><span class="sig-paren">(</span><em class="sig-param">sub</em><span class="optional">[</span>, <em class="sig-param">start</em><span class="optional">[</span>, <em class="sig-param">end</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#bytearray.index" title="永久链接至目标">¶</a></dt>
<dd><p>类似于 <a class="reference internal" href="#bytes.find" title="bytes.find"><code class="xref py py-meth docutils literal notranslate"><span class="pre">find()</span></code></a>，但在找不到子序列时会引发 <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>。</p>
<p>要搜索的子序列可以是任意 <a class="reference internal" href="../glossary.html#term-bytes-like-object"><span class="xref std std-term">bytes-like object</span></a> 或是 0 至 255 范围内的整数。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.3 版更改: </span>也接受 0 至 255 范围内的整数作为子序列。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="bytes.join">
<code class="sig-prename descclassname">bytes.</code><code class="sig-name descname">join</code><span class="sig-paren">(</span><em class="sig-param">iterable</em><span class="sig-paren">)</span><a class="headerlink" href="#bytes.join" title="永久链接至目标">¶</a></dt>
<dt id="bytearray.join">
<code class="sig-prename descclassname">bytearray.</code><code class="sig-name descname">join</code><span class="sig-paren">(</span><em class="sig-param">iterable</em><span class="sig-paren">)</span><a class="headerlink" href="#bytearray.join" title="永久链接至目标">¶</a></dt>
<dd><p>返回一个由 <em>iterable</em> 中的二进制数据序列拼接而成的 bytes 或 bytearray 对象。 如果 <em>iterable</em> 中存在任何非 <a class="reference internal" href="../glossary.html#term-bytes-like-object"><span class="xref std std-term">字节类对象</span></a> 包括存在 <a class="reference internal" href="#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> 对象值则会引发 <a class="reference internal" href="exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>。 提供该方法的 bytes 或 bytearray 对象的内容将作为元素之间的分隔。</p>
</dd></dl>

<dl class="method">
<dt id="bytes.maketrans">
<em class="property">static </em><code class="sig-prename descclassname">bytes.</code><code class="sig-name descname">maketrans</code><span class="sig-paren">(</span><em class="sig-param">from</em>, <em class="sig-param">to</em><span class="sig-paren">)</span><a class="headerlink" href="#bytes.maketrans" title="永久链接至目标">¶</a></dt>
<dt id="bytearray.maketrans">
<em class="property">static </em><code class="sig-prename descclassname">bytearray.</code><code class="sig-name descname">maketrans</code><span class="sig-paren">(</span><em class="sig-param">from</em>, <em class="sig-param">to</em><span class="sig-paren">)</span><a class="headerlink" href="#bytearray.maketrans" title="永久链接至目标">¶</a></dt>
<dd><p>此静态方法返回一个可用于 <a class="reference internal" href="#bytes.translate" title="bytes.translate"><code class="xref py py-meth docutils literal notranslate"><span class="pre">bytes.translate()</span></code></a> 的转换对照表，它将把 <em>from</em> 中的每个字符映射为 <em>to</em> 中相同位置上的字符；<em>from</em> 与 <em>to</em> 必须都是 <a class="reference internal" href="../glossary.html#term-bytes-like-object"><span class="xref std std-term">字节类对象</span></a> 并且具有相同的长度。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.1 新版功能.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="bytes.partition">
<code class="sig-prename descclassname">bytes.</code><code class="sig-name descname">partition</code><span class="sig-paren">(</span><em class="sig-param">sep</em><span class="sig-paren">)</span><a class="headerlink" href="#bytes.partition" title="永久链接至目标">¶</a></dt>
<dt id="bytearray.partition">
<code class="sig-prename descclassname">bytearray.</code><code class="sig-name descname">partition</code><span class="sig-paren">(</span><em class="sig-param">sep</em><span class="sig-paren">)</span><a class="headerlink" href="#bytearray.partition" title="永久链接至目标">¶</a></dt>
<dd><p>在 <em>sep</em> 首次出现的位置拆分序列，返回一个 3 元组，其中包含分隔符之前的部分、分隔符本身或其 bytearray 副本，以及分隔符之后的部分。 如果分隔符未找到，则返回的 3 元组中包含原序列以及两个空的 bytes 或 bytearray 对象。</p>
<p>要搜索的分隔符可以是任意 <a class="reference internal" href="../glossary.html#term-bytes-like-object"><span class="xref std std-term">bytes-like object</span></a>。</p>
</dd></dl>

<dl class="method">
<dt id="bytes.replace">
<code class="sig-prename descclassname">bytes.</code><code class="sig-name descname">replace</code><span class="sig-paren">(</span><em class="sig-param">old</em>, <em class="sig-param">new</em><span class="optional">[</span>, <em class="sig-param">count</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#bytes.replace" title="永久链接至目标">¶</a></dt>
<dt id="bytearray.replace">
<code class="sig-prename descclassname">bytearray.</code><code class="sig-name descname">replace</code><span class="sig-paren">(</span><em class="sig-param">old</em>, <em class="sig-param">new</em><span class="optional">[</span>, <em class="sig-param">count</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#bytearray.replace" title="永久链接至目标">¶</a></dt>
<dd><p>返回序列的副本，其中出现的所有子序列 <em>old</em> 都将被替换为 <em>new</em>。 如果给出了可选参数 <em>count</em>，则只替换前 <em>count</em> 次出现。</p>
<p>要搜索的子序列及其替换序列可以是任意 <a class="reference internal" href="../glossary.html#term-bytes-like-object"><span class="xref std std-term">bytes-like object</span></a>。</p>
<div class="admonition note">
<p class="admonition-title">注解</p>
<p>此方法的 bytearray 版本 <em>并非</em> 原地操作 —— 它总是产生一个新对象，即便没有做任何改变。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="bytes.rfind">
<code class="sig-prename descclassname">bytes.</code><code class="sig-name descname">rfind</code><span class="sig-paren">(</span><em class="sig-param">sub</em><span class="optional">[</span>, <em class="sig-param">start</em><span class="optional">[</span>, <em class="sig-param">end</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#bytes.rfind" title="永久链接至目标">¶</a></dt>
<dt id="bytearray.rfind">
<code class="sig-prename descclassname">bytearray.</code><code class="sig-name descname">rfind</code><span class="sig-paren">(</span><em class="sig-param">sub</em><span class="optional">[</span>, <em class="sig-param">start</em><span class="optional">[</span>, <em class="sig-param">end</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#bytearray.rfind" title="永久链接至目标">¶</a></dt>
<dd><p>返回子序列 <em>sub</em> 在序列内被找到的最大（最右）索引，这样 <em>sub</em> 将包含在 <code class="docutils literal notranslate"><span class="pre">s[start:end]</span></code> 当中。 可选参数 <em>start</em> 与 <em>end</em> 会被解读为切片表示法。 如果未找到则返回 <code class="docutils literal notranslate"><span class="pre">-1</span></code>。</p>
<p>要搜索的子序列可以是任意 <a class="reference internal" href="../glossary.html#term-bytes-like-object"><span class="xref std std-term">bytes-like object</span></a> 或是 0 至 255 范围内的整数。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.3 版更改: </span>也接受 0 至 255 范围内的整数作为子序列。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="bytes.rindex">
<code class="sig-prename descclassname">bytes.</code><code class="sig-name descname">rindex</code><span class="sig-paren">(</span><em class="sig-param">sub</em><span class="optional">[</span>, <em class="sig-param">start</em><span class="optional">[</span>, <em class="sig-param">end</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#bytes.rindex" title="永久链接至目标">¶</a></dt>
<dt id="bytearray.rindex">
<code class="sig-prename descclassname">bytearray.</code><code class="sig-name descname">rindex</code><span class="sig-paren">(</span><em class="sig-param">sub</em><span class="optional">[</span>, <em class="sig-param">start</em><span class="optional">[</span>, <em class="sig-param">end</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#bytearray.rindex" title="永久链接至目标">¶</a></dt>
<dd><p>类似于 <a class="reference internal" href="#bytes.rfind" title="bytes.rfind"><code class="xref py py-meth docutils literal notranslate"><span class="pre">rfind()</span></code></a>，但在子序列 <em>sub</em> 未找到时会引发 <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>。</p>
<p>要搜索的子序列可以是任意 <a class="reference internal" href="../glossary.html#term-bytes-like-object"><span class="xref std std-term">bytes-like object</span></a> 或是 0 至 255 范围内的整数。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.3 版更改: </span>也接受 0 至 255 范围内的整数作为子序列。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="bytes.rpartition">
<code class="sig-prename descclassname">bytes.</code><code class="sig-name descname">rpartition</code><span class="sig-paren">(</span><em class="sig-param">sep</em><span class="sig-paren">)</span><a class="headerlink" href="#bytes.rpartition" title="永久链接至目标">¶</a></dt>
<dt id="bytearray.rpartition">
<code class="sig-prename descclassname">bytearray.</code><code class="sig-name descname">rpartition</code><span class="sig-paren">(</span><em class="sig-param">sep</em><span class="sig-paren">)</span><a class="headerlink" href="#bytearray.rpartition" title="永久链接至目标">¶</a></dt>
<dd><p>在 <em>sep</em> 最后一次出现的位置拆分序列，返回一个 3 元组，其中包含分隔符之前的部分，分隔符本身或其 bytearray 副本，以及分隔符之后的部分。 如果分隔符未找到，则返回的 3 元组中包含两个空的 bytes 或 bytearray 对象以及原序列的副本。</p>
<p>要搜索的分隔符可以是任意 <a class="reference internal" href="../glossary.html#term-bytes-like-object"><span class="xref std std-term">bytes-like object</span></a>。</p>
</dd></dl>

<dl class="method">
<dt id="bytes.startswith">
<code class="sig-prename descclassname">bytes.</code><code class="sig-name descname">startswith</code><span class="sig-paren">(</span><em class="sig-param">prefix</em><span class="optional">[</span>, <em class="sig-param">start</em><span class="optional">[</span>, <em class="sig-param">end</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#bytes.startswith" title="永久链接至目标">¶</a></dt>
<dt id="bytearray.startswith">
<code class="sig-prename descclassname">bytearray.</code><code class="sig-name descname">startswith</code><span class="sig-paren">(</span><em class="sig-param">prefix</em><span class="optional">[</span>, <em class="sig-param">start</em><span class="optional">[</span>, <em class="sig-param">end</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#bytearray.startswith" title="永久链接至目标">¶</a></dt>
<dd><p>如果二进制数据以指定的 <em>prefix</em> 开头则返回 <code class="docutils literal notranslate"><span class="pre">True</span></code>，否则返回 <code class="docutils literal notranslate"><span class="pre">False</span></code>。 <em>prefix</em> 也可以为由多个供查找的前缀构成的元组。 如果有可选项 <em>start</em>，将从所指定位置开始检查。 如果有可选项 <em>end</em>，将在所指定位置停止比较。</p>
<p>要搜索的前缀可以是任意 <a class="reference internal" href="../glossary.html#term-bytes-like-object"><span class="xref std std-term">bytes-like object</span></a>。</p>
</dd></dl>

<dl class="method">
<dt id="bytes.translate">
<code class="sig-prename descclassname">bytes.</code><code class="sig-name descname">translate</code><span class="sig-paren">(</span><em class="sig-param">table</em>, <em class="sig-param">delete=b''</em><span class="sig-paren">)</span><a class="headerlink" href="#bytes.translate" title="永久链接至目标">¶</a></dt>
<dt id="bytearray.translate">
<code class="sig-prename descclassname">bytearray.</code><code class="sig-name descname">translate</code><span class="sig-paren">(</span><em class="sig-param">table</em>, <em class="sig-param">delete=b''</em><span class="sig-paren">)</span><a class="headerlink" href="#bytearray.translate" title="永久链接至目标">¶</a></dt>
<dd><p>返回原 bytes 或 bytearray 对象的副本，移除其中所有在可选参数 <em>delete</em> 中出现的 bytes，其余 bytes 将通过给定的转换表进行映射，该转换表必须是长度为 256 的 bytes 对象。</p>
<p>你可以使用 <a class="reference internal" href="#bytes.maketrans" title="bytes.maketrans"><code class="xref py py-func docutils literal notranslate"><span class="pre">bytes.maketrans()</span></code></a> 方法来创建转换表。</p>
<p>对于仅需移除字符的转换，请将 <em>table</em> 参数设为 <code class="docutils literal notranslate"><span class="pre">None</span></code>:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="sa">b</span><span class="s1">&#39;read this short text&#39;</span><span class="o">.</span><span class="n">translate</span><span class="p">(</span><span class="kc">None</span><span class="p">,</span> <span class="sa">b</span><span class="s1">&#39;aeiou&#39;</span><span class="p">)</span>
<span class="go">b&#39;rd ths shrt txt&#39;</span>
</pre></div>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.6 版更改: </span>现在支持将 <em>delete</em> 作为关键字参数。</p>
</div>
</dd></dl>

<p>以下 bytes 和 bytearray 对象的方法的默认行为会假定使用兼容 ASCII 的二进制格式，但通过传入适当的参数仍然可用于任意二进制数据。 请注意本小节中所有的 bytearray 方法都 <em>不是</em> 原地执行操作，而是会产生新的对象。</p>
<dl class="method">
<dt id="bytes.center">
<code class="sig-prename descclassname">bytes.</code><code class="sig-name descname">center</code><span class="sig-paren">(</span><em class="sig-param">width</em><span class="optional">[</span>, <em class="sig-param">fillbyte</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#bytes.center" title="永久链接至目标">¶</a></dt>
<dt id="bytearray.center">
<code class="sig-prename descclassname">bytearray.</code><code class="sig-name descname">center</code><span class="sig-paren">(</span><em class="sig-param">width</em><span class="optional">[</span>, <em class="sig-param">fillbyte</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#bytearray.center" title="永久链接至目标">¶</a></dt>
<dd><p>返回原对象的副本，在长度为 <em>width</em> 的序列内居中，使用指定的 <em>fillbyte</em> 填充两边的空位（默认使用 ASCII 空格符）。 对于 <a class="reference internal" href="#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> 对象，如果 <em>width</em> 小于等于 <code class="docutils literal notranslate"><span class="pre">len(s)</span></code> 则返回原序列的副本。</p>
<div class="admonition note">
<p class="admonition-title">注解</p>
<p>此方法的 bytearray 版本 <em>并非</em> 原地操作 —— 它总是产生一个新对象，即便没有做任何改变。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="bytes.ljust">
<code class="sig-prename descclassname">bytes.</code><code class="sig-name descname">ljust</code><span class="sig-paren">(</span><em class="sig-param">width</em><span class="optional">[</span>, <em class="sig-param">fillbyte</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#bytes.ljust" title="永久链接至目标">¶</a></dt>
<dt id="bytearray.ljust">
<code class="sig-prename descclassname">bytearray.</code><code class="sig-name descname">ljust</code><span class="sig-paren">(</span><em class="sig-param">width</em><span class="optional">[</span>, <em class="sig-param">fillbyte</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#bytearray.ljust" title="永久链接至目标">¶</a></dt>
<dd><p>反回原对象的副本，在长度为 <em>width</em> 的序列中靠左对齐。 使用指定的 <em>fillbyte</em> 填充空位（默认使用 ASCII 空格符）。 对于 <a class="reference internal" href="#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> 对象，如果 <em>width</em> 小于等于 <code class="docutils literal notranslate"><span class="pre">len(s)</span></code> 则返回原序列的副本。</p>
<div class="admonition note">
<p class="admonition-title">注解</p>
<p>此方法的 bytearray 版本 <em>并非</em> 原地操作 —— 它总是产生一个新对象，即便没有做任何改变。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="bytes.lstrip">
<code class="sig-prename descclassname">bytes.</code><code class="sig-name descname">lstrip</code><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param">chars</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#bytes.lstrip" title="永久链接至目标">¶</a></dt>
<dt id="bytearray.lstrip">
<code class="sig-prename descclassname">bytearray.</code><code class="sig-name descname">lstrip</code><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param">chars</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#bytearray.lstrip" title="永久链接至目标">¶</a></dt>
<dd><p>返回原序列的副本，移除指定的前导字节。 <em>chars</em> 参数为指定要移除字节值集合的二进制序列 —— 这个名称表明此方法通常是用于 ASCII 字符。 如果省略或为 <code class="docutils literal notranslate"><span class="pre">None</span></code>，则 <em>chars</em> 参数默认移除 ASCII 空白符。 <em>chars</em> 参数并非指定单个前缀；而是会移除参数值的所有组合:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="sa">b</span><span class="s1">&#39;   spacious   &#39;</span><span class="o">.</span><span class="n">lstrip</span><span class="p">()</span>
<span class="go">b&#39;spacious   &#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="sa">b</span><span class="s1">&#39;www.example.com&#39;</span><span class="o">.</span><span class="n">lstrip</span><span class="p">(</span><span class="sa">b</span><span class="s1">&#39;cmowz.&#39;</span><span class="p">)</span>
<span class="go">b&#39;example.com&#39;</span>
</pre></div>
</div>
<p>要移除的字节值二进制序列可以是任意 <a class="reference internal" href="../glossary.html#term-bytes-like-object"><span class="xref std std-term">bytes-like object</span></a>。</p>
<div class="admonition note">
<p class="admonition-title">注解</p>
<p>此方法的 bytearray 版本 <em>并非</em> 原地操作 —— 它总是产生一个新对象，即便没有做任何改变。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="bytes.rjust">
<code class="sig-prename descclassname">bytes.</code><code class="sig-name descname">rjust</code><span class="sig-paren">(</span><em class="sig-param">width</em><span class="optional">[</span>, <em class="sig-param">fillbyte</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#bytes.rjust" title="永久链接至目标">¶</a></dt>
<dt id="bytearray.rjust">
<code class="sig-prename descclassname">bytearray.</code><code class="sig-name descname">rjust</code><span class="sig-paren">(</span><em class="sig-param">width</em><span class="optional">[</span>, <em class="sig-param">fillbyte</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#bytearray.rjust" title="永久链接至目标">¶</a></dt>
<dd><p>返回原对象的副本，在长度为 <em>width</em> 的序列中靠右对齐。 使用指定的 <em>fillbyte</em> 填充空位（默认使用 ASCII 空格符）。 对于 <a class="reference internal" href="#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> 对象，如果 <em>width</em> 小于等于 <code class="docutils literal notranslate"><span class="pre">len(s)</span></code> 则返回原序列的副本。</p>
<div class="admonition note">
<p class="admonition-title">注解</p>
<p>此方法的 bytearray 版本 <em>并非</em> 原地操作 —— 它总是产生一个新对象，即便没有做任何改变。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="bytes.rsplit">
<code class="sig-prename descclassname">bytes.</code><code class="sig-name descname">rsplit</code><span class="sig-paren">(</span><em class="sig-param">sep=None</em>, <em class="sig-param">maxsplit=-1</em><span class="sig-paren">)</span><a class="headerlink" href="#bytes.rsplit" title="永久链接至目标">¶</a></dt>
<dt id="bytearray.rsplit">
<code class="sig-prename descclassname">bytearray.</code><code class="sig-name descname">rsplit</code><span class="sig-paren">(</span><em class="sig-param">sep=None</em>, <em class="sig-param">maxsplit=-1</em><span class="sig-paren">)</span><a class="headerlink" href="#bytearray.rsplit" title="永久链接至目标">¶</a></dt>
<dd><p>将二进制序列拆分为相同类型的子序列，使用 <em>sep</em> 作为分隔符。 如果给出了 <em>maxsplit</em>，则最多进行 <em>maxsplit</em> 次拆分，从 <em>最右边</em> 开始。 如果 <em>sep</em> 未指定或为 <code class="docutils literal notranslate"><span class="pre">None</span></code>，任何只包含 ASCII 空白符的子序列都会被作为分隔符。 除了从右边开始拆分，<a class="reference internal" href="#bytearray.rsplit" title="bytearray.rsplit"><code class="xref py py-meth docutils literal notranslate"><span class="pre">rsplit()</span></code></a> 的其他行为都类似于下文所述的 <a class="reference internal" href="#bytearray.split" title="bytearray.split"><code class="xref py py-meth docutils literal notranslate"><span class="pre">split()</span></code></a>。</p>
</dd></dl>

<dl class="method">
<dt id="bytes.rstrip">
<code class="sig-prename descclassname">bytes.</code><code class="sig-name descname">rstrip</code><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param">chars</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#bytes.rstrip" title="永久链接至目标">¶</a></dt>
<dt id="bytearray.rstrip">
<code class="sig-prename descclassname">bytearray.</code><code class="sig-name descname">rstrip</code><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param">chars</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#bytearray.rstrip" title="永久链接至目标">¶</a></dt>
<dd><p>返回原序列的副本，移除指定的末尾字节。 <em>chars</em> 参数为指定要移除字节值集合的二进制序列 —— 这个名称表明此方法通常是用于 ASCII 字符。 如果省略或为 <code class="docutils literal notranslate"><span class="pre">None</span></code>，则 <em>chars</em> 参数默认移除 ASCII 空白符。 <em>chars</em> 参数并非指定单个后缀；而是会移除参数值的所有组合:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="sa">b</span><span class="s1">&#39;   spacious   &#39;</span><span class="o">.</span><span class="n">rstrip</span><span class="p">()</span>
<span class="go">b&#39;   spacious&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="sa">b</span><span class="s1">&#39;mississippi&#39;</span><span class="o">.</span><span class="n">rstrip</span><span class="p">(</span><span class="sa">b</span><span class="s1">&#39;ipz&#39;</span><span class="p">)</span>
<span class="go">b&#39;mississ&#39;</span>
</pre></div>
</div>
<p>要移除的字节值二进制序列可以是任意 <a class="reference internal" href="../glossary.html#term-bytes-like-object"><span class="xref std std-term">bytes-like object</span></a>。</p>
<div class="admonition note">
<p class="admonition-title">注解</p>
<p>此方法的 bytearray 版本 <em>并非</em> 原地操作 —— 它总是产生一个新对象，即便没有做任何改变。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="bytes.split">
<code class="sig-prename descclassname">bytes.</code><code class="sig-name descname">split</code><span class="sig-paren">(</span><em class="sig-param">sep=None</em>, <em class="sig-param">maxsplit=-1</em><span class="sig-paren">)</span><a class="headerlink" href="#bytes.split" title="永久链接至目标">¶</a></dt>
<dt id="bytearray.split">
<code class="sig-prename descclassname">bytearray.</code><code class="sig-name descname">split</code><span class="sig-paren">(</span><em class="sig-param">sep=None</em>, <em class="sig-param">maxsplit=-1</em><span class="sig-paren">)</span><a class="headerlink" href="#bytearray.split" title="永久链接至目标">¶</a></dt>
<dd><p>将二进制序列拆分为相同类型的子序列，使用 <em>sep</em> 作为分隔符。 如果给出了 <em>maxsplit</em> 且非负值，则最多进行 <em>maxsplit</em> 次拆分（因此，列表最多会有 <code class="docutils literal notranslate"><span class="pre">maxsplit+1</span></code> 个元素）。 如果 <em>maxsplit</em> 未指定或为 <code class="docutils literal notranslate"><span class="pre">-1</span></code>，则不限制拆分次数（进行所有可能的拆分）。</p>
<p>如果给出了 <em>sep</em>，则连续的分隔符不会被组合在一起而是被视为分隔空子序列 (例如 <code class="docutils literal notranslate"><span class="pre">b'1,,2'.split(b',')</span></code> 将返回 <code class="docutils literal notranslate"><span class="pre">[b'1',</span> <span class="pre">b'',</span> <span class="pre">b'2']</span></code>)。 <em>sep</em> 参数可能为一个多字节序列 (例如 <code class="docutils literal notranslate"><span class="pre">b'1&lt;&gt;2&lt;&gt;3'.split(b'&lt;&gt;')</span></code> 将返回 <code class="docutils literal notranslate"><span class="pre">[b'1',</span> <span class="pre">b'2',</span> <span class="pre">b'3']</span></code>)。 使用指定的分隔符拆分空序列将返回 <code class="docutils literal notranslate"><span class="pre">[b'']</span></code> 或 <code class="docutils literal notranslate"><span class="pre">[bytearray(b'')]</span></code>，具体取决于被拆分对象的类型。 <em>sep</em> 参数可以是任意 <a class="reference internal" href="../glossary.html#term-bytes-like-object"><span class="xref std std-term">bytes-like object</span></a>。</p>
<p>例如</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="sa">b</span><span class="s1">&#39;1,2,3&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="sa">b</span><span class="s1">&#39;,&#39;</span><span class="p">)</span>
<span class="go">[b&#39;1&#39;, b&#39;2&#39;, b&#39;3&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="sa">b</span><span class="s1">&#39;1,2,3&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="sa">b</span><span class="s1">&#39;,&#39;</span><span class="p">,</span> <span class="n">maxsplit</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="go">[b&#39;1&#39;, b&#39;2,3&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="sa">b</span><span class="s1">&#39;1,2,,3,&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="sa">b</span><span class="s1">&#39;,&#39;</span><span class="p">)</span>
<span class="go">[b&#39;1&#39;, b&#39;2&#39;, b&#39;&#39;, b&#39;3&#39;, b&#39;&#39;]</span>
</pre></div>
</div>
<p>如果 <em>sep</em> 未指定或为 <code class="docutils literal notranslate"><span class="pre">None</span></code>，则会应用另一种拆分算法：连续的 ASCII 空白符会被视为单个分隔符，其结果将不包含序列开头或末尾的空白符。 因此，在不指定分隔符的情况下对空序列或仅包含 ASCII 空白符的序列进行拆分将返回 <code class="docutils literal notranslate"><span class="pre">[]</span></code>。</p>
<p>例如</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="sa">b</span><span class="s1">&#39;1 2 3&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">()</span>
<span class="go">[b&#39;1&#39;, b&#39;2&#39;, b&#39;3&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="sa">b</span><span class="s1">&#39;1 2 3&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="n">maxsplit</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="go">[b&#39;1&#39;, b&#39;2 3&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="sa">b</span><span class="s1">&#39;   1   2   3   &#39;</span><span class="o">.</span><span class="n">split</span><span class="p">()</span>
<span class="go">[b&#39;1&#39;, b&#39;2&#39;, b&#39;3&#39;]</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="bytes.strip">
<code class="sig-prename descclassname">bytes.</code><code class="sig-name descname">strip</code><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param">chars</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#bytes.strip" title="永久链接至目标">¶</a></dt>
<dt id="bytearray.strip">
<code class="sig-prename descclassname">bytearray.</code><code class="sig-name descname">strip</code><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param">chars</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#bytearray.strip" title="永久链接至目标">¶</a></dt>
<dd><p>返回原序列的副本，移除指定的开头和末尾字节。 <em>chars</em> 参数为指定要移除字节值集合的二进制序列 —— 这个名称表明此方法通常是用于 ASCII 字符。 如果省略或为 <code class="docutils literal notranslate"><span class="pre">None</span></code>，则 <em>chars</em> 参数默认移除 ASCII 空白符。 <em>chars</em> 参数并非指定单个前缀或后缀；而是会移除参数值的所有组合:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="sa">b</span><span class="s1">&#39;   spacious   &#39;</span><span class="o">.</span><span class="n">strip</span><span class="p">()</span>
<span class="go">b&#39;spacious&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="sa">b</span><span class="s1">&#39;www.example.com&#39;</span><span class="o">.</span><span class="n">strip</span><span class="p">(</span><span class="sa">b</span><span class="s1">&#39;cmowz.&#39;</span><span class="p">)</span>
<span class="go">b&#39;example&#39;</span>
</pre></div>
</div>
<p>要移除的字节值二进制序列可以是任意 <a class="reference internal" href="../glossary.html#term-bytes-like-object"><span class="xref std std-term">bytes-like object</span></a>。</p>
<div class="admonition note">
<p class="admonition-title">注解</p>
<p>此方法的 bytearray 版本 <em>并非</em> 原地操作 —— 它总是产生一个新对象，即便没有做任何改变。</p>
</div>
</dd></dl>

<p>以下 bytes 和 bytearray 对象的方法会假定使用兼容 ASCII 的二进制格式，不应当被应用于任意二进制数据。 请注意本小节中所有的 bytearray 方法都 <em>不是</em> 原地执行操作，而是会产生新的对象。</p>
<dl class="method">
<dt id="bytes.capitalize">
<code class="sig-prename descclassname">bytes.</code><code class="sig-name descname">capitalize</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#bytes.capitalize" title="永久链接至目标">¶</a></dt>
<dt id="bytearray.capitalize">
<code class="sig-prename descclassname">bytearray.</code><code class="sig-name descname">capitalize</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#bytearray.capitalize" title="永久链接至目标">¶</a></dt>
<dd><p>返回原序列的副本，其中每个字节将都将被解读为一个 ASCII 字符，并且第一个字节的字符大写而其余的小写。 非 ASCII 字节值将保持原样不变。</p>
<div class="admonition note">
<p class="admonition-title">注解</p>
<p>此方法的 bytearray 版本 <em>并非</em> 原地操作 —— 它总是产生一个新对象，即便没有做任何改变。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="bytes.expandtabs">
<code class="sig-prename descclassname">bytes.</code><code class="sig-name descname">expandtabs</code><span class="sig-paren">(</span><em class="sig-param">tabsize=8</em><span class="sig-paren">)</span><a class="headerlink" href="#bytes.expandtabs" title="永久链接至目标">¶</a></dt>
<dt id="bytearray.expandtabs">
<code class="sig-prename descclassname">bytearray.</code><code class="sig-name descname">expandtabs</code><span class="sig-paren">(</span><em class="sig-param">tabsize=8</em><span class="sig-paren">)</span><a class="headerlink" href="#bytearray.expandtabs" title="永久链接至目标">¶</a></dt>
<dd><p>返回序列的副本，其中所有的 ASCII 制表符会由一个或多个 ASCII 空格替换，具体取决于当前列位置和给定的制表符宽度。 每 <em>tabsize</em> 个字节设为一个制表位（默认值 8 时设定的制表位在列 0, 8, 16 依次类推）。 要展开序列，当前列位置将被设为零并逐一检查序列中的每个字节。 如果字节为 ASCII 制表符 (<code class="docutils literal notranslate"><span class="pre">b'\t'</span></code>)，则并在结果中插入一个或多个空格符，直到当前列等于下一个制表位。 （制表符本身不会被复制。） 如果当前字节为 ASCII 换行符 (<code class="docutils literal notranslate"><span class="pre">b'\n'</span></code>) 或回车符 (<code class="docutils literal notranslate"><span class="pre">b'\r'</span></code>)，它会被复制并将当前列重设为零。 任何其他字节会被不加修改地复制并将当前列加一，不论该字节值在被打印时会如何显示:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="sa">b</span><span class="s1">&#39;01</span><span class="se">\t</span><span class="s1">012</span><span class="se">\t</span><span class="s1">0123</span><span class="se">\t</span><span class="s1">01234&#39;</span><span class="o">.</span><span class="n">expandtabs</span><span class="p">()</span>
<span class="go">b&#39;01      012     0123    01234&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="sa">b</span><span class="s1">&#39;01</span><span class="se">\t</span><span class="s1">012</span><span class="se">\t</span><span class="s1">0123</span><span class="se">\t</span><span class="s1">01234&#39;</span><span class="o">.</span><span class="n">expandtabs</span><span class="p">(</span><span class="mi">4</span><span class="p">)</span>
<span class="go">b&#39;01  012 0123    01234&#39;</span>
</pre></div>
</div>
<div class="admonition note">
<p class="admonition-title">注解</p>
<p>此方法的 bytearray 版本 <em>并非</em> 原地操作 —— 它总是产生一个新对象，即便没有做任何改变。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="bytes.isalnum">
<code class="sig-prename descclassname">bytes.</code><code class="sig-name descname">isalnum</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#bytes.isalnum" title="永久链接至目标">¶</a></dt>
<dt id="bytearray.isalnum">
<code class="sig-prename descclassname">bytearray.</code><code class="sig-name descname">isalnum</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#bytearray.isalnum" title="永久链接至目标">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if all bytes in the sequence are alphabetical ASCII characters
or ASCII decimal digits and the sequence is not empty, <code class="docutils literal notranslate"><span class="pre">False</span></code> otherwise.
Alphabetic ASCII characters are those byte values in the sequence
<code class="docutils literal notranslate"><span class="pre">b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'</span></code>. ASCII decimal
digits are those byte values in the sequence <code class="docutils literal notranslate"><span class="pre">b'0123456789'</span></code>.</p>
<p>例如</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="sa">b</span><span class="s1">&#39;ABCabc1&#39;</span><span class="o">.</span><span class="n">isalnum</span><span class="p">()</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="sa">b</span><span class="s1">&#39;ABC abc1&#39;</span><span class="o">.</span><span class="n">isalnum</span><span class="p">()</span>
<span class="go">False</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="bytes.isalpha">
<code class="sig-prename descclassname">bytes.</code><code class="sig-name descname">isalpha</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#bytes.isalpha" title="永久链接至目标">¶</a></dt>
<dt id="bytearray.isalpha">
<code class="sig-prename descclassname">bytearray.</code><code class="sig-name descname">isalpha</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#bytearray.isalpha" title="永久链接至目标">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if all bytes in the sequence are alphabetic ASCII characters
and the sequence is not empty, <code class="docutils literal notranslate"><span class="pre">False</span></code> otherwise.  Alphabetic ASCII
characters are those byte values in the sequence
<code class="docutils literal notranslate"><span class="pre">b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'</span></code>.</p>
<p>例如</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="sa">b</span><span class="s1">&#39;ABCabc&#39;</span><span class="o">.</span><span class="n">isalpha</span><span class="p">()</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="sa">b</span><span class="s1">&#39;ABCabc1&#39;</span><span class="o">.</span><span class="n">isalpha</span><span class="p">()</span>
<span class="go">False</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="bytes.isascii">
<code class="sig-prename descclassname">bytes.</code><code class="sig-name descname">isascii</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#bytes.isascii" title="永久链接至目标">¶</a></dt>
<dt id="bytearray.isascii">
<code class="sig-prename descclassname">bytearray.</code><code class="sig-name descname">isascii</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#bytearray.isascii" title="永久链接至目标">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the sequence is empty or all bytes in the sequence are ASCII,
<code class="docutils literal notranslate"><span class="pre">False</span></code> otherwise.
ASCII bytes are in the range 0-0x7F.</p>
<div class="versionadded">
<p><span class="versionmodified added">3.7 新版功能.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="bytes.isdigit">
<code class="sig-prename descclassname">bytes.</code><code class="sig-name descname">isdigit</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#bytes.isdigit" title="永久链接至目标">¶</a></dt>
<dt id="bytearray.isdigit">
<code class="sig-prename descclassname">bytearray.</code><code class="sig-name descname">isdigit</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#bytearray.isdigit" title="永久链接至目标">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if all bytes in the sequence are ASCII decimal digits
and the sequence is not empty, <code class="docutils literal notranslate"><span class="pre">False</span></code> otherwise. ASCII decimal digits are
those byte values in the sequence <code class="docutils literal notranslate"><span class="pre">b'0123456789'</span></code>.</p>
<p>例如</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="sa">b</span><span class="s1">&#39;1234&#39;</span><span class="o">.</span><span class="n">isdigit</span><span class="p">()</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="sa">b</span><span class="s1">&#39;1.23&#39;</span><span class="o">.</span><span class="n">isdigit</span><span class="p">()</span>
<span class="go">False</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="bytes.islower">
<code class="sig-prename descclassname">bytes.</code><code class="sig-name descname">islower</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#bytes.islower" title="永久链接至目标">¶</a></dt>
<dt id="bytearray.islower">
<code class="sig-prename descclassname">bytearray.</code><code class="sig-name descname">islower</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#bytearray.islower" title="永久链接至目标">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if there is at least one lowercase ASCII character
in the sequence and no uppercase ASCII characters, <code class="docutils literal notranslate"><span class="pre">False</span></code> otherwise.</p>
<p>例如</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="sa">b</span><span class="s1">&#39;hello world&#39;</span><span class="o">.</span><span class="n">islower</span><span class="p">()</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="sa">b</span><span class="s1">&#39;Hello world&#39;</span><span class="o">.</span><span class="n">islower</span><span class="p">()</span>
<span class="go">False</span>
</pre></div>
</div>
<p>小写 ASCII 字符就是字节值包含在序列 <code class="docutils literal notranslate"><span class="pre">b'abcdefghijklmnopqrstuvwxyz'</span></code> 中的字符。 大写 ASCII 字符就是字节值包含在序列 <code class="docutils literal notranslate"><span class="pre">b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'</span></code> 中的字符。</p>
</dd></dl>

<dl class="method">
<dt id="bytes.isspace">
<code class="sig-prename descclassname">bytes.</code><code class="sig-name descname">isspace</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#bytes.isspace" title="永久链接至目标">¶</a></dt>
<dt id="bytearray.isspace">
<code class="sig-prename descclassname">bytearray.</code><code class="sig-name descname">isspace</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#bytearray.isspace" title="永久链接至目标">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if all bytes in the sequence are ASCII whitespace and the
sequence is not empty, <code class="docutils literal notranslate"><span class="pre">False</span></code> otherwise.  ASCII whitespace characters are
those byte values in the sequence <code class="docutils literal notranslate"><span class="pre">b'</span> <span class="pre">\t\n\r\x0b\f'</span></code> (space, tab, newline,
carriage return, vertical tab, form feed).</p>
</dd></dl>

<dl class="method">
<dt id="bytes.istitle">
<code class="sig-prename descclassname">bytes.</code><code class="sig-name descname">istitle</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#bytes.istitle" title="永久链接至目标">¶</a></dt>
<dt id="bytearray.istitle">
<code class="sig-prename descclassname">bytearray.</code><code class="sig-name descname">istitle</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#bytearray.istitle" title="永久链接至目标">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the sequence is ASCII titlecase and the sequence is not
empty, <code class="docutils literal notranslate"><span class="pre">False</span></code> otherwise. See <a class="reference internal" href="#bytes.title" title="bytes.title"><code class="xref py py-meth docutils literal notranslate"><span class="pre">bytes.title()</span></code></a> for more details on the
definition of &quot;titlecase&quot;.</p>
<p>例如</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="sa">b</span><span class="s1">&#39;Hello World&#39;</span><span class="o">.</span><span class="n">istitle</span><span class="p">()</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="sa">b</span><span class="s1">&#39;Hello world&#39;</span><span class="o">.</span><span class="n">istitle</span><span class="p">()</span>
<span class="go">False</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="bytes.isupper">
<code class="sig-prename descclassname">bytes.</code><code class="sig-name descname">isupper</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#bytes.isupper" title="永久链接至目标">¶</a></dt>
<dt id="bytearray.isupper">
<code class="sig-prename descclassname">bytearray.</code><code class="sig-name descname">isupper</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#bytearray.isupper" title="永久链接至目标">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if there is at least one uppercase alphabetic ASCII character
in the sequence and no lowercase ASCII characters, <code class="docutils literal notranslate"><span class="pre">False</span></code> otherwise.</p>
<p>例如</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="sa">b</span><span class="s1">&#39;HELLO WORLD&#39;</span><span class="o">.</span><span class="n">isupper</span><span class="p">()</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="sa">b</span><span class="s1">&#39;Hello world&#39;</span><span class="o">.</span><span class="n">isupper</span><span class="p">()</span>
<span class="go">False</span>
</pre></div>
</div>
<p>小写 ASCII 字符就是字节值包含在序列 <code class="docutils literal notranslate"><span class="pre">b'abcdefghijklmnopqrstuvwxyz'</span></code> 中的字符。 大写 ASCII 字符就是字节值包含在序列 <code class="docutils literal notranslate"><span class="pre">b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'</span></code> 中的字符。</p>
</dd></dl>

<dl class="method">
<dt id="bytes.lower">
<code class="sig-prename descclassname">bytes.</code><code class="sig-name descname">lower</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#bytes.lower" title="永久链接至目标">¶</a></dt>
<dt id="bytearray.lower">
<code class="sig-prename descclassname">bytearray.</code><code class="sig-name descname">lower</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#bytearray.lower" title="永久链接至目标">¶</a></dt>
<dd><p>返回原序列的副本，其所有大写 ASCII 字符均转换为对应的小写形式。</p>
<p>例如</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="sa">b</span><span class="s1">&#39;Hello World&#39;</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span>
<span class="go">b&#39;hello world&#39;</span>
</pre></div>
</div>
<p>小写 ASCII 字符就是字节值包含在序列 <code class="docutils literal notranslate"><span class="pre">b'abcdefghijklmnopqrstuvwxyz'</span></code> 中的字符。 大写 ASCII 字符就是字节值包含在序列 <code class="docutils literal notranslate"><span class="pre">b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'</span></code> 中的字符。</p>
<div class="admonition note">
<p class="admonition-title">注解</p>
<p>此方法的 bytearray 版本 <em>并非</em> 原地操作 —— 它总是产生一个新对象，即便没有做任何改变。</p>
</div>
</dd></dl>

<span class="target" id="index-42"></span><dl class="method">
<dt id="bytes.splitlines">
<code class="sig-prename descclassname">bytes.</code><code class="sig-name descname">splitlines</code><span class="sig-paren">(</span><em class="sig-param">keepends=False</em><span class="sig-paren">)</span><a class="headerlink" href="#bytes.splitlines" title="永久链接至目标">¶</a></dt>
<dt id="bytearray.splitlines">
<code class="sig-prename descclassname">bytearray.</code><code class="sig-name descname">splitlines</code><span class="sig-paren">(</span><em class="sig-param">keepends=False</em><span class="sig-paren">)</span><a class="headerlink" href="#bytearray.splitlines" title="永久链接至目标">¶</a></dt>
<dd><p>返回由原二进制序列中各行组成的列表，在 ASCII 行边界符的位置拆分。 此方法使用 <a class="reference internal" href="../glossary.html#term-universal-newlines"><span class="xref std std-term">universal newlines</span></a> 方式来分行。 结果列表中不包含换行符，除非给出了 <em>keepends</em> 且为真值。</p>
<p>例如</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="sa">b</span><span class="s1">&#39;ab c</span><span class="se">\n\n</span><span class="s1">de fg</span><span class="se">\r</span><span class="s1">kl</span><span class="se">\r\n</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">splitlines</span><span class="p">()</span>
<span class="go">[b&#39;ab c&#39;, b&#39;&#39;, b&#39;de fg&#39;, b&#39;kl&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="sa">b</span><span class="s1">&#39;ab c</span><span class="se">\n\n</span><span class="s1">de fg</span><span class="se">\r</span><span class="s1">kl</span><span class="se">\r\n</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">splitlines</span><span class="p">(</span><span class="n">keepends</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="go">[b&#39;ab c\n&#39;, b&#39;\n&#39;, b&#39;de fg\r&#39;, b&#39;kl\r\n&#39;]</span>
</pre></div>
</div>
<p>不同于 <a class="reference internal" href="#bytes.split" title="bytes.split"><code class="xref py py-meth docutils literal notranslate"><span class="pre">split()</span></code></a>，当给出了分隔符 <em>sep</em> 时，对于空字符串此方法将返回一个空列表，而末尾的换行不会令结果中增加额外的行:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="sa">b</span><span class="s2">&quot;&quot;</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="sa">b</span><span class="s1">&#39;</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">),</span> <span class="sa">b</span><span class="s2">&quot;Two lines</span><span class="se">\n</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="sa">b</span><span class="s1">&#39;</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">)</span>
<span class="go">([b&#39;&#39;], [b&#39;Two lines&#39;, b&#39;&#39;])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="sa">b</span><span class="s2">&quot;&quot;</span><span class="o">.</span><span class="n">splitlines</span><span class="p">(),</span> <span class="sa">b</span><span class="s2">&quot;One line</span><span class="se">\n</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">splitlines</span><span class="p">()</span>
<span class="go">([], [b&#39;One line&#39;])</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="bytes.swapcase">
<code class="sig-prename descclassname">bytes.</code><code class="sig-name descname">swapcase</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#bytes.swapcase" title="永久链接至目标">¶</a></dt>
<dt id="bytearray.swapcase">
<code class="sig-prename descclassname">bytearray.</code><code class="sig-name descname">swapcase</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#bytearray.swapcase" title="永久链接至目标">¶</a></dt>
<dd><p>返回原序列的副本，其所有小写 ASCII 字符均转换为对应的大写形式，反之亦反。</p>
<p>例如</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="sa">b</span><span class="s1">&#39;Hello World&#39;</span><span class="o">.</span><span class="n">swapcase</span><span class="p">()</span>
<span class="go">b&#39;hELLO wORLD&#39;</span>
</pre></div>
</div>
<p>小写 ASCII 字符就是字节值包含在序列 <code class="docutils literal notranslate"><span class="pre">b'abcdefghijklmnopqrstuvwxyz'</span></code> 中的字符。 大写 ASCII 字符就是字节值包含在序列 <code class="docutils literal notranslate"><span class="pre">b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'</span></code> 中的字符。</p>
<p>不同于 <a class="reference internal" href="#str.swapcase" title="str.swapcase"><code class="xref py py-func docutils literal notranslate"><span class="pre">str.swapcase()</span></code></a>，在些二进制版本下 <code class="docutils literal notranslate"><span class="pre">bin.swapcase().swapcase()</span> <span class="pre">==</span> <span class="pre">bin</span></code> 总是成立。 大小写转换在 ASCII 中是对称的，即使其对于任意 Unicode 码位来说并不总是成立。</p>
<div class="admonition note">
<p class="admonition-title">注解</p>
<p>此方法的 bytearray 版本 <em>并非</em> 原地操作 —— 它总是产生一个新对象，即便没有做任何改变。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="bytes.title">
<code class="sig-prename descclassname">bytes.</code><code class="sig-name descname">title</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#bytes.title" title="永久链接至目标">¶</a></dt>
<dt id="bytearray.title">
<code class="sig-prename descclassname">bytearray.</code><code class="sig-name descname">title</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#bytearray.title" title="永久链接至目标">¶</a></dt>
<dd><p>返回原二进制序列的标题版本，其中每个单词以一个大写 ASCII 字符为开头，其余字母为小写。 不区别大小写的字节值将保持原样不变。</p>
<p>例如</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="sa">b</span><span class="s1">&#39;Hello world&#39;</span><span class="o">.</span><span class="n">title</span><span class="p">()</span>
<span class="go">b&#39;Hello World&#39;</span>
</pre></div>
</div>
<p>小写 ASCII 字符就是字节值包含在序列 <code class="docutils literal notranslate"><span class="pre">b'abcdefghijklmnopqrstuvwxyz'</span></code> 中的字符。 大写 ASCII 字符就是字节值包含在序列 <code class="docutils literal notranslate"><span class="pre">b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'</span></code> 中的字符。 所有其他字节值都不区分大小写。</p>
<p>该算法使用一种简单的与语言无关的定义，将连续的字母组合视为单词。 该定义在多数情况下都很有效，但它也意味着代表缩写形式与所有格的撇号也会成为单词边界，这可能导致不希望的结果:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="sa">b</span><span class="s2">&quot;they&#39;re bill&#39;s friends from the UK&quot;</span><span class="o">.</span><span class="n">title</span><span class="p">()</span>
<span class="go">b&quot;They&#39;Re Bill&#39;S Friends From The Uk&quot;</span>
</pre></div>
</div>
<p>可以使用正则表达式来构建针对撇号的特别处理:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">re</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">titlecase</span><span class="p">(</span><span class="n">s</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">return</span> <span class="n">re</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="sa">rb</span><span class="s2">&quot;[A-Za-z]+(&#39;[A-Za-z]+)?&quot;</span><span class="p">,</span>
<span class="gp">... </span>                  <span class="k">lambda</span> <span class="n">mo</span><span class="p">:</span> <span class="n">mo</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">0</span><span class="p">)[</span><span class="mi">0</span><span class="p">:</span><span class="mi">1</span><span class="p">]</span><span class="o">.</span><span class="n">upper</span><span class="p">()</span> <span class="o">+</span>
<span class="gp">... </span>                             <span class="n">mo</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">0</span><span class="p">)[</span><span class="mi">1</span><span class="p">:]</span><span class="o">.</span><span class="n">lower</span><span class="p">(),</span>
<span class="gp">... </span>                  <span class="n">s</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">titlecase</span><span class="p">(</span><span class="sa">b</span><span class="s2">&quot;they&#39;re bill&#39;s friends.&quot;</span><span class="p">)</span>
<span class="go">b&quot;They&#39;re Bill&#39;s Friends.&quot;</span>
</pre></div>
</div>
<div class="admonition note">
<p class="admonition-title">注解</p>
<p>此方法的 bytearray 版本 <em>并非</em> 原地操作 —— 它总是产生一个新对象，即便没有做任何改变。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="bytes.upper">
<code class="sig-prename descclassname">bytes.</code><code class="sig-name descname">upper</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#bytes.upper" title="永久链接至目标">¶</a></dt>
<dt id="bytearray.upper">
<code class="sig-prename descclassname">bytearray.</code><code class="sig-name descname">upper</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#bytearray.upper" title="永久链接至目标">¶</a></dt>
<dd><p>返回原序列的副本，其所有小写 ASCII 字符均转换为对应的大写形式。</p>
<p>例如</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="sa">b</span><span class="s1">&#39;Hello World&#39;</span><span class="o">.</span><span class="n">upper</span><span class="p">()</span>
<span class="go">b&#39;HELLO WORLD&#39;</span>
</pre></div>
</div>
<p>小写 ASCII 字符就是字节值包含在序列 <code class="docutils literal notranslate"><span class="pre">b'abcdefghijklmnopqrstuvwxyz'</span></code> 中的字符。 大写 ASCII 字符就是字节值包含在序列 <code class="docutils literal notranslate"><span class="pre">b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'</span></code> 中的字符。</p>
<div class="admonition note">
<p class="admonition-title">注解</p>
<p>此方法的 bytearray 版本 <em>并非</em> 原地操作 —— 它总是产生一个新对象，即便没有做任何改变。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="bytes.zfill">
<code class="sig-prename descclassname">bytes.</code><code class="sig-name descname">zfill</code><span class="sig-paren">(</span><em class="sig-param">width</em><span class="sig-paren">)</span><a class="headerlink" href="#bytes.zfill" title="永久链接至目标">¶</a></dt>
<dt id="bytearray.zfill">
<code class="sig-prename descclassname">bytearray.</code><code class="sig-name descname">zfill</code><span class="sig-paren">(</span><em class="sig-param">width</em><span class="sig-paren">)</span><a class="headerlink" href="#bytearray.zfill" title="永久链接至目标">¶</a></dt>
<dd><p>返回原序列的副本，在左边填充 <code class="docutils literal notranslate"><span class="pre">b'0'</span></code> 数码使序列长度为 <em>width</em>。 正负值前缀 (<code class="docutils literal notranslate"><span class="pre">b'+'</span></code>/ <code class="docutils literal notranslate"><span class="pre">b'-'</span></code>) 的处理方式是在正负符号 <em>之后</em> 填充而非在之前。 对于 <a class="reference internal" href="#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> 对象，如果 <em>width</em> 小于等于 <code class="docutils literal notranslate"><span class="pre">len(seq)</span></code> 则返回原序列。</p>
<p>例如</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="sa">b</span><span class="s2">&quot;42&quot;</span><span class="o">.</span><span class="n">zfill</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span>
<span class="go">b&#39;00042&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="sa">b</span><span class="s2">&quot;-42&quot;</span><span class="o">.</span><span class="n">zfill</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span>
<span class="go">b&#39;-0042&#39;</span>
</pre></div>
</div>
<div class="admonition note">
<p class="admonition-title">注解</p>
<p>此方法的 bytearray 版本 <em>并非</em> 原地操作 —— 它总是产生一个新对象，即便没有做任何改变。</p>
</div>
</dd></dl>

</div>
<div class="section" id="printf-style-bytes-formatting">
<span id="bytes-formatting"></span><h3><code class="docutils literal notranslate"><span class="pre">printf</span></code> 风格的字节串格式化<a class="headerlink" href="#printf-style-bytes-formatting" title="永久链接至标题">¶</a></h3>
<div class="admonition note" id="index-43">
<p class="admonition-title">注解</p>
<p>此处介绍的格式化操作具有多种怪异特性，可能导致许多常见错误（例如无法正确显示元组和字典）。 如果要打印的值可能为元组或字典，请将其放入一个元组中。</p>
</div>
<p>字节串对象 (<code class="docutils literal notranslate"><span class="pre">bytes</span></code>/<code class="docutils literal notranslate"><span class="pre">bytearray</span></code>) 具有一种特殊的内置操作：使用 <code class="docutils literal notranslate"><span class="pre">%</span></code> (取模) 运算符。 这也被称为字节串的 <em>格式化</em> 或 <em>插值</em> 运算符。 对于 <code class="docutils literal notranslate"><span class="pre">format</span> <span class="pre">%</span> <span class="pre">values</span></code> (其中 <em>format</em> 为一个字节串对象)，在 <em>format</em> 中的 <code class="docutils literal notranslate"><span class="pre">%</span></code> 转换标记符将被替换为零个或多个 <em>values</em> 条目。 其效果类似于在 C 语言中使用 <code class="xref c c-func docutils literal notranslate"><span class="pre">sprintf()</span></code>。</p>
<p>如果 <em>format</em> 要求一个单独参数，则 <em>values</em> 可以为一个非元组对象。 <a class="footnote-reference brackets" href="#id16" id="id11">5</a>  否则的话，<em>values</em> 必须或是是一个包含项数与格式字节串对象中指定的转换符项数相同的元组，或者是一个单独的映射对象（例如元组）。</p>
<p id="index-44">转换标记符包含两个或更多字符并具有以下组成，且必须遵循此处规定的顺序：</p>
<ol class="arabic simple">
<li><p><code class="docutils literal notranslate"><span class="pre">'%'</span></code> 字符，用于标记转换符的起始。</p></li>
<li><p>映射键（可选），由加圆括号的字符序列组成 (例如 <code class="docutils literal notranslate"><span class="pre">(somename)</span></code>)。</p></li>
<li><p>转换旗标（可选），用于影响某些转换类型的结果。</p></li>
<li><p>最小字段宽度（可选）。 如果指定为 <code class="docutils literal notranslate"><span class="pre">'*'</span></code> (星号)，则实际宽度会从 <em>values</em> 元组的下一元素中读取，要转换的对象则为最小字段宽度和可选的精度之后的元素。</p></li>
<li><p>精度（可选），以在 <code class="docutils literal notranslate"><span class="pre">'.'</span></code> (点号) 之后加精度值的形式给出。 如果指定为 <code class="docutils literal notranslate"><span class="pre">'*'</span></code> (星号)，则实际精度会从 <em>values</em> 元组的下一元素中读取，要转换的对象则为精度之后的元素。</p></li>
<li><p>长度修饰符（可选）。</p></li>
<li><p>转换类型。</p></li>
</ol>
<p>当右边的参数为一个字典（或其他映射类型）时，字节串对象中的格式 <em>必须</em> 包含加圆括号的映射键，对应 <code class="docutils literal notranslate"><span class="pre">'%'</span></code> 字符之后字典中的每一项。 映射键将从映射中选取要格式化的值。 例如：</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="sa">b</span><span class="s1">&#39;</span><span class="si">%(language)s</span><span class="s1"> has </span><span class="si">%(number)03d</span><span class="s1"> quote types.&#39;</span> <span class="o">%</span>
<span class="gp">... </span>      <span class="p">{</span><span class="sa">b</span><span class="s1">&#39;language&#39;</span><span class="p">:</span> <span class="sa">b</span><span class="s2">&quot;Python&quot;</span><span class="p">,</span> <span class="sa">b</span><span class="s2">&quot;number&quot;</span><span class="p">:</span> <span class="mi">2</span><span class="p">})</span>
<span class="go">b&#39;Python has 002 quote types.&#39;</span>
</pre></div>
</div>
<p>在此情况下格式中不能出现 <code class="docutils literal notranslate"><span class="pre">*</span></code> 标记符（因其需要一个序列类的参数列表）。</p>
<p>转换旗标为：</p>
<table class="docutils align-default" id="index-45">
<colgroup>
<col style="width: 12%" />
<col style="width: 88%" />
</colgroup>
<thead>
<tr class="row-odd"><th class="head"><p>标志</p></th>
<th class="head"><p>含义</p></th>
</tr>
</thead>
<tbody>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">'#'</span></code></p></td>
<td><p>值的转换将使用“替代形式”（具体定义见下文）。</p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">'0'</span></code></p></td>
<td><p>转换将为数字值填充零字符。</p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">'-'</span></code></p></td>
<td><p>转换值将靠左对齐（如果同时给出 <code class="docutils literal notranslate"><span class="pre">'0'</span></code> 转换，则会覆盖后者）。</p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">'</span> <span class="pre">'</span></code></p></td>
<td><p>(空格) 符号位转换产生的正数（或空字符串）前将留出一个空格。</p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">'+'</span></code></p></td>
<td><p>符号字符 (<code class="docutils literal notranslate"><span class="pre">'+'</span></code> 或 <code class="docutils literal notranslate"><span class="pre">'-'</span></code>) 将显示于转换结果的开头（会覆盖 &quot;空格&quot; 旗标）。</p></td>
</tr>
</tbody>
</table>
<p>可以给出长度修饰符 (<code class="docutils literal notranslate"><span class="pre">h</span></code>, <code class="docutils literal notranslate"><span class="pre">l</span></code> 或 <code class="docutils literal notranslate"><span class="pre">L</span></code>)，但会被忽略，因为对 Python 来说没有必要 -- 所以 <code class="docutils literal notranslate"><span class="pre">%ld</span></code> 等价于 <code class="docutils literal notranslate"><span class="pre">%d</span></code>。</p>
<p>转换类型为：</p>
<table class="docutils align-default">
<colgroup>
<col style="width: 17%" />
<col style="width: 74%" />
<col style="width: 10%" />
</colgroup>
<thead>
<tr class="row-odd"><th class="head"><p>转换符</p></th>
<th class="head"><p>含义</p></th>
<th class="head"><p>注释</p></th>
</tr>
</thead>
<tbody>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">'d'</span></code></p></td>
<td><p>有符号十进制整数。</p></td>
<td></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">'i'</span></code></p></td>
<td><p>有符号十进制整数。</p></td>
<td></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">'o'</span></code></p></td>
<td><p>有符号八进制数。</p></td>
<td><p>(1)</p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">'u'</span></code></p></td>
<td><p>过时类型 -- 等价于 <code class="docutils literal notranslate"><span class="pre">'d'</span></code>。</p></td>
<td><p>(8)</p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">'x'</span></code></p></td>
<td><p>有符号十六进制数（小写）。</p></td>
<td><p>(2)</p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">'X'</span></code></p></td>
<td><p>有符号十六进制数（大写）。</p></td>
<td><p>(2)</p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">'e'</span></code></p></td>
<td><p>浮点指数格式（小写）。</p></td>
<td><p>(3)</p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">'E'</span></code></p></td>
<td><p>浮点指数格式（大写）。</p></td>
<td><p>(3)</p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">'f'</span></code></p></td>
<td><p>浮点十进制格式。</p></td>
<td><p>(3)</p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">'F'</span></code></p></td>
<td><p>浮点十进制格式。</p></td>
<td><p>(3)</p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">'g'</span></code></p></td>
<td><p>浮点格式。 如果指数小于 -4 或不小于精度则使用小写指数格式，否则使用十进制格式。</p></td>
<td><p>(4)</p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">'G'</span></code></p></td>
<td><p>浮点格式。 如果指数小于 -4 或不小于精度则使用大写指数格式，否则使用十进制格式。</p></td>
<td><p>(4)</p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">'c'</span></code></p></td>
<td><p>单个字节（接受整数或单个字节对象）。</p></td>
<td></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">'b'</span></code></p></td>
<td><p>字节串（任何遵循 <a class="reference internal" href="../c-api/buffer.html#bufferobjects"><span class="std std-ref">缓冲区协议</span></a> 或是具有 <a class="reference internal" href="../reference/datamodel.html#object.__bytes__" title="object.__bytes__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__bytes__()</span></code></a> 的对象）。</p></td>
<td><p>(5)</p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">'s'</span></code></p></td>
<td><p><code class="docutils literal notranslate"><span class="pre">'s'</span></code> 是 <code class="docutils literal notranslate"><span class="pre">'b'</span></code> 的一个别名，只应当在基于 Python2/3 的代码中使用。</p></td>
<td><p>(6)</p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">'a'</span></code></p></td>
<td><p>字节串（使用 <code class="docutils literal notranslate"><span class="pre">repr(obj).encode('ascii','backslashreplace)</span></code> 转换任何 Python 对象）。</p></td>
<td><p>(5)</p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">'r'</span></code></p></td>
<td><p><code class="docutils literal notranslate"><span class="pre">'r'</span></code> 是 <code class="docutils literal notranslate"><span class="pre">'a'</span></code> 的一个别名，只应当在基于 Python2/3 的代码中使用。</p></td>
<td><p>(7)</p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">'%'</span></code></p></td>
<td><p>不转换参数，在结果中输出一个 <code class="docutils literal notranslate"><span class="pre">'%'</span></code> 字符。</p></td>
<td></td>
</tr>
</tbody>
</table>
<p>注释:</p>
<ol class="arabic">
<li><p>此替代形式会在第一个数码之前插入标示八进制数的前缀 (<code class="docutils literal notranslate"><span class="pre">'0o'</span></code>)。</p></li>
<li><p>此替代形式会在第一个数码之前插入 <code class="docutils literal notranslate"><span class="pre">'0x'</span></code> 或 <code class="docutils literal notranslate"><span class="pre">'0X'</span></code> 前缀（取决于是使用 <code class="docutils literal notranslate"><span class="pre">'x'</span></code> 还是 <code class="docutils literal notranslate"><span class="pre">'X'</span></code> 格式）。</p></li>
<li><p>此替代形式总是会在结果中包含一个小数点，即使其后并没有数码。</p>
<p>小数点后的数码位数由精度决定，默认为 6。</p>
</li>
<li><p>此替代形式总是会在结果中包含一个小数点，末尾各位的零不会如其他情况下那样被移除。</p>
<p>小数点前后的有效数码位数由精度决定，默认为 6。</p>
</li>
<li><p>如果精度为 <code class="docutils literal notranslate"><span class="pre">N</span></code>，输出将截短为 <code class="docutils literal notranslate"><span class="pre">N</span></code> 个字符。</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">b'%s'</span></code> 已弃用，但在 3.x 系列中将不会被移除。</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">b'%r'</span></code> 已弃用，但在 3.x 系列中将不会被移除。</p></li>
<li><p>参见 <span class="target" id="index-65"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0237"><strong>PEP 237</strong></a>。</p></li>
</ol>
<div class="admonition note">
<p class="admonition-title">注解</p>
<p>此方法的 bytearray 版本 <em>并非</em> 原地操作 —— 它总是产生一个新对象，即便没有做任何改变。</p>
</div>
<div class="admonition seealso">
<p class="admonition-title">参见</p>
<p><span class="target" id="index-66"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0461"><strong>PEP 461</strong></a> - 为 bytes 和 bytearray 添加 % 格式化</p>
</div>
<div class="versionadded">
<p><span class="versionmodified added">3.5 新版功能.</span></p>
</div>
</div>
<div class="section" id="memory-views">
<span id="typememoryview"></span><h3>内存视图<a class="headerlink" href="#memory-views" title="永久链接至标题">¶</a></h3>
<p><a class="reference internal" href="#memoryview" title="memoryview"><code class="xref py py-class docutils literal notranslate"><span class="pre">memoryview</span></code></a> 对象允许 Python 代码访问一个对象的内部数据，只要该对象支持 <a class="reference internal" href="../c-api/buffer.html#bufferobjects"><span class="std std-ref">缓冲区协议</span></a> 而无需进行拷贝。</p>
<dl class="class">
<dt id="memoryview">
<em class="property">class </em><code class="sig-name descname">memoryview</code><span class="sig-paren">(</span><em class="sig-param">obj</em><span class="sig-paren">)</span><a class="headerlink" href="#memoryview" title="永久链接至目标">¶</a></dt>
<dd><p>创建一个引用 <em>obj</em> 的 <a class="reference internal" href="#memoryview" title="memoryview"><code class="xref py py-class docutils literal notranslate"><span class="pre">memoryview</span></code></a>。 <em>obj</em> 必须支持缓冲区协议。 支持缓冲区协议的内置对象包括 <a class="reference internal" href="#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> 和 <a class="reference internal" href="#bytearray" title="bytearray"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytearray</span></code></a>。</p>
<p><a class="reference internal" href="#memoryview" title="memoryview"><code class="xref py py-class docutils literal notranslate"><span class="pre">memoryview</span></code></a> 具有 <em>元素</em> 的概念，即由原始对象 <em>obj</em> 所处理的基本内存单元。 对于许多简单类型例如 <a class="reference internal" href="#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> 和 <a class="reference internal" href="#bytearray" title="bytearray"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytearray</span></code></a> 来说，一个元素就是一个字节，但是其他的类型例如 <a class="reference internal" href="array.html#array.array" title="array.array"><code class="xref py py-class docutils literal notranslate"><span class="pre">array.array</span></code></a> 可能有更大的元素。</p>
<p><code class="docutils literal notranslate"><span class="pre">len(view)</span></code> 与 <a class="reference internal" href="#memoryview.tolist" title="memoryview.tolist"><code class="xref py py-class docutils literal notranslate"><span class="pre">tolist</span></code></a> 的长度相等。 如果 <code class="docutils literal notranslate"><span class="pre">view.ndim</span> <span class="pre">=</span> <span class="pre">0</span></code>，则其长度为 1。 如果 <code class="docutils literal notranslate"><span class="pre">view.ndim</span> <span class="pre">=</span> <span class="pre">1</span></code>，则其长度等于 view 中元素的数量。 对于更高的维度，其长度等于表示 view 的嵌套列表的长度。 <a class="reference internal" href="#memoryview.itemsize" title="memoryview.itemsize"><code class="xref py py-class docutils literal notranslate"><span class="pre">itemsize</span></code></a> 属性可向你给出单个元素所占的字节数。</p>
<p><a class="reference internal" href="#memoryview" title="memoryview"><code class="xref py py-class docutils literal notranslate"><span class="pre">memoryview</span></code></a> 支持通过切片和索引访问其元素。 一维切片的结果将是一个子视图:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">v</span> <span class="o">=</span> <span class="nb">memoryview</span><span class="p">(</span><span class="sa">b</span><span class="s1">&#39;abcefg&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">v</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span>
<span class="go">98</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">v</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>
<span class="go">103</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">v</span><span class="p">[</span><span class="mi">1</span><span class="p">:</span><span class="mi">4</span><span class="p">]</span>
<span class="go">&lt;memory at 0x7f3ddc9f4350&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">bytes</span><span class="p">(</span><span class="n">v</span><span class="p">[</span><span class="mi">1</span><span class="p">:</span><span class="mi">4</span><span class="p">])</span>
<span class="go">b&#39;bce&#39;</span>
</pre></div>
</div>
<p>如果 <a class="reference internal" href="#memoryview.format" title="memoryview.format"><code class="xref py py-class docutils literal notranslate"><span class="pre">format</span></code></a> 是一个来自于 <a class="reference internal" href="struct.html#module-struct" title="struct: Interpret bytes as packed binary data."><code class="xref py py-mod docutils literal notranslate"><span class="pre">struct</span></code></a> 模块的原生格式说明符，则也支持使用整数或由整数构成的元组进行索引，并返回具有正确类型的单个 <em>元素</em>。 一维内存视图可以使用一个整数或由一个整数构成的元组进行索引。 多维内存视图可以使用由恰好 <em>ndim</em> 个整数构成的元素进行索引，<em>ndim</em> 即其维度。 零维内存视图可以使用空元组进行索引。</p>
<p>这里是一个使用非字节格式的例子:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">array</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="n">array</span><span class="o">.</span><span class="n">array</span><span class="p">(</span><span class="s1">&#39;l&#39;</span><span class="p">,</span> <span class="p">[</span><span class="o">-</span><span class="mi">11111111</span><span class="p">,</span> <span class="mi">22222222</span><span class="p">,</span> <span class="o">-</span><span class="mi">33333333</span><span class="p">,</span> <span class="mi">44444444</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="nb">memoryview</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
<span class="go">-11111111</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>
<span class="go">44444444</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="p">[::</span><span class="mi">2</span><span class="p">]</span><span class="o">.</span><span class="n">tolist</span><span class="p">()</span>
<span class="go">[-11111111, -33333333]</span>
</pre></div>
</div>
<p>如果下层对象是可写的，则内存视图支持一维切片赋值。 改变大小则不被允许:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">data</span> <span class="o">=</span> <span class="nb">bytearray</span><span class="p">(</span><span class="sa">b</span><span class="s1">&#39;abcefg&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">v</span> <span class="o">=</span> <span class="nb">memoryview</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">v</span><span class="o">.</span><span class="n">readonly</span>
<span class="go">False</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">v</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="nb">ord</span><span class="p">(</span><span class="sa">b</span><span class="s1">&#39;z&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">data</span>
<span class="go">bytearray(b&#39;zbcefg&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">v</span><span class="p">[</span><span class="mi">1</span><span class="p">:</span><span class="mi">4</span><span class="p">]</span> <span class="o">=</span> <span class="sa">b</span><span class="s1">&#39;123&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">data</span>
<span class="go">bytearray(b&#39;z123fg&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">v</span><span class="p">[</span><span class="mi">2</span><span class="p">:</span><span class="mi">3</span><span class="p">]</span> <span class="o">=</span> <span class="sa">b</span><span class="s1">&#39;spam&#39;</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">ValueError</span>: <span class="n">memoryview assignment: lvalue and rvalue have different structures</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">v</span><span class="p">[</span><span class="mi">2</span><span class="p">:</span><span class="mi">6</span><span class="p">]</span> <span class="o">=</span> <span class="sa">b</span><span class="s1">&#39;spam&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">data</span>
<span class="go">bytearray(b&#39;z1spam&#39;)</span>
</pre></div>
</div>
<p>由带有格式符号 'B', 'b' 或 'c' 的可哈希（只读）类型构成的一维内存视图同样是可哈希的。 哈希定义为 <code class="docutils literal notranslate"><span class="pre">hash(m)</span> <span class="pre">==</span> <span class="pre">hash(m.tobytes())</span></code>:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">v</span> <span class="o">=</span> <span class="nb">memoryview</span><span class="p">(</span><span class="sa">b</span><span class="s1">&#39;abcefg&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">hash</span><span class="p">(</span><span class="n">v</span><span class="p">)</span> <span class="o">==</span> <span class="nb">hash</span><span class="p">(</span><span class="sa">b</span><span class="s1">&#39;abcefg&#39;</span><span class="p">)</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">hash</span><span class="p">(</span><span class="n">v</span><span class="p">[</span><span class="mi">2</span><span class="p">:</span><span class="mi">4</span><span class="p">])</span> <span class="o">==</span> <span class="nb">hash</span><span class="p">(</span><span class="sa">b</span><span class="s1">&#39;ce&#39;</span><span class="p">)</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">hash</span><span class="p">(</span><span class="n">v</span><span class="p">[::</span><span class="o">-</span><span class="mi">2</span><span class="p">])</span> <span class="o">==</span> <span class="nb">hash</span><span class="p">(</span><span class="sa">b</span><span class="s1">&#39;abcefg&#39;</span><span class="p">[::</span><span class="o">-</span><span class="mi">2</span><span class="p">])</span>
<span class="go">True</span>
</pre></div>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.3 版更改: </span>一维内存视图现在可以被切片。 带有格式符号 'B', 'b' 或 'c' 的一维内存视图现在是可哈希的。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.4 版更改: </span>内存视图现在会自动注册为 <a class="reference internal" href="collections.abc.html#collections.abc.Sequence" title="collections.abc.Sequence"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.abc.Sequence</span></code></a></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.5 版更改: </span>内存视图现在可使用整数元组进行索引。</p>
</div>
<p><a class="reference internal" href="#memoryview" title="memoryview"><code class="xref py py-class docutils literal notranslate"><span class="pre">memoryview</span></code></a> 具有以下一些方法：</p>
<dl class="method">
<dt id="memoryview.__eq__">
<code class="sig-name descname">__eq__</code><span class="sig-paren">(</span><em class="sig-param">exporter</em><span class="sig-paren">)</span><a class="headerlink" href="#memoryview.__eq__" title="永久链接至目标">¶</a></dt>
<dd><p>memoryview 与 <span class="target" id="index-67"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3118"><strong>PEP 3118</strong></a> 中的导出器这两者如果形状相同，并且如果当使用 <a class="reference internal" href="struct.html#module-struct" title="struct: Interpret bytes as packed binary data."><code class="xref py py-mod docutils literal notranslate"><span class="pre">struct</span></code></a> 语法解读操作数的相应格式代码时所有对应值都相同，则它们就是等价的。</p>
<p>对于 <a class="reference internal" href="#memoryview.tolist" title="memoryview.tolist"><code class="xref py py-meth docutils literal notranslate"><span class="pre">tolist()</span></code></a> 当前所支持的 <a class="reference internal" href="struct.html#module-struct" title="struct: Interpret bytes as packed binary data."><code class="xref py py-mod docutils literal notranslate"><span class="pre">struct</span></code></a> 格式字符串子集，如果 <code class="docutils literal notranslate"><span class="pre">v.tolist()</span> <span class="pre">==</span> <span class="pre">w.tolist()</span></code> 则 <code class="docutils literal notranslate"><span class="pre">v</span></code> 和 <code class="docutils literal notranslate"><span class="pre">w</span></code> 相等:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">array</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="n">array</span><span class="o">.</span><span class="n">array</span><span class="p">(</span><span class="s1">&#39;I&#39;</span><span class="p">,</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="n">array</span><span class="o">.</span><span class="n">array</span><span class="p">(</span><span class="s1">&#39;d&#39;</span><span class="p">,</span> <span class="p">[</span><span class="mf">1.0</span><span class="p">,</span> <span class="mf">2.0</span><span class="p">,</span> <span class="mf">3.0</span><span class="p">,</span> <span class="mf">4.0</span><span class="p">,</span> <span class="mf">5.0</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">array</span><span class="o">.</span><span class="n">array</span><span class="p">(</span><span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="p">[</span><span class="mi">5</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">1</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="nb">memoryview</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span> <span class="o">=</span> <span class="nb">memoryview</span><span class="p">(</span><span class="n">b</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">==</span> <span class="n">a</span> <span class="o">==</span> <span class="n">y</span> <span class="o">==</span> <span class="n">b</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span><span class="o">.</span><span class="n">tolist</span><span class="p">()</span> <span class="o">==</span> <span class="n">a</span><span class="o">.</span><span class="n">tolist</span><span class="p">()</span> <span class="o">==</span> <span class="n">y</span><span class="o">.</span><span class="n">tolist</span><span class="p">()</span> <span class="o">==</span> <span class="n">b</span><span class="o">.</span><span class="n">tolist</span><span class="p">()</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">z</span> <span class="o">=</span> <span class="n">y</span><span class="p">[::</span><span class="o">-</span><span class="mi">2</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">z</span> <span class="o">==</span> <span class="n">c</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">z</span><span class="o">.</span><span class="n">tolist</span><span class="p">()</span> <span class="o">==</span> <span class="n">c</span><span class="o">.</span><span class="n">tolist</span><span class="p">()</span>
<span class="go">True</span>
</pre></div>
</div>
<p>如果两边的格式字符串都不被 <a class="reference internal" href="struct.html#module-struct" title="struct: Interpret bytes as packed binary data."><code class="xref py py-mod docutils literal notranslate"><span class="pre">struct</span></code></a> 模块所支持，则两对象比较结果总是不相等（即使格式字符串和缓冲区内容相同）:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">ctypes</span> <span class="kn">import</span> <span class="n">BigEndianStructure</span><span class="p">,</span> <span class="n">c_long</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">BEPoint</span><span class="p">(</span><span class="n">BigEndianStructure</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">_fields_</span> <span class="o">=</span> <span class="p">[(</span><span class="s2">&quot;x&quot;</span><span class="p">,</span> <span class="n">c_long</span><span class="p">),</span> <span class="p">(</span><span class="s2">&quot;y&quot;</span><span class="p">,</span> <span class="n">c_long</span><span class="p">)]</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">point</span> <span class="o">=</span> <span class="n">BEPoint</span><span class="p">(</span><span class="mi">100</span><span class="p">,</span> <span class="mi">200</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="nb">memoryview</span><span class="p">(</span><span class="n">point</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="nb">memoryview</span><span class="p">(</span><span class="n">point</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">==</span> <span class="n">point</span>
<span class="go">False</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">==</span> <span class="n">b</span>
<span class="go">False</span>
</pre></div>
</div>
<p>请注意，与浮点数的情况一样，对于内存视图对象来说，<code class="docutils literal notranslate"><span class="pre">v</span> <span class="pre">is</span> <span class="pre">w</span></code> 也 <em>并不</em> 意味着 <code class="docutils literal notranslate"><span class="pre">v</span> <span class="pre">==</span> <span class="pre">w</span></code>。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.3 版更改: </span>之前的版本比较原始内存时会忽略条目的格式与逻辑数组结构。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="memoryview.tobytes">
<code class="sig-name descname">tobytes</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#memoryview.tobytes" title="永久链接至目标">¶</a></dt>
<dd><p>将缓冲区中的数据作为字节串返回。 这相当于在内存视图上调用 <a class="reference internal" href="#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> 构造器。</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="nb">memoryview</span><span class="p">(</span><span class="sa">b</span><span class="s2">&quot;abc&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">tobytes</span><span class="p">()</span>
<span class="go">b&#39;abc&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">bytes</span><span class="p">(</span><span class="n">m</span><span class="p">)</span>
<span class="go">b&#39;abc&#39;</span>
</pre></div>
</div>
<p>对于非连续数组，结果等于平面化表示的列表，其中所有元素都转换为字节串。 <a class="reference internal" href="#memoryview.tobytes" title="memoryview.tobytes"><code class="xref py py-meth docutils literal notranslate"><span class="pre">tobytes()</span></code></a> 支持所有格式字符串，不符合 <a class="reference internal" href="struct.html#module-struct" title="struct: Interpret bytes as packed binary data."><code class="xref py py-mod docutils literal notranslate"><span class="pre">struct</span></code></a> 模块语法的那些也包括在内。</p>
</dd></dl>

<dl class="method">
<dt id="memoryview.hex">
<code class="sig-name descname">hex</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#memoryview.hex" title="永久链接至目标">¶</a></dt>
<dd><p>返回一个字符串对象，其中分别以两个十六进制数码表示缓冲区里的每个字节。</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="nb">memoryview</span><span class="p">(</span><span class="sa">b</span><span class="s2">&quot;abc&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">hex</span><span class="p">()</span>
<span class="go">&#39;616263&#39;</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified added">3.5 新版功能.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="memoryview.tolist">
<code class="sig-name descname">tolist</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#memoryview.tolist" title="永久链接至目标">¶</a></dt>
<dd><p>将缓冲区内的数据以一个元素列表的形式返回。</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">memoryview</span><span class="p">(</span><span class="sa">b</span><span class="s1">&#39;abc&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">tolist</span><span class="p">()</span>
<span class="go">[97, 98, 99]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">array</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="n">array</span><span class="o">.</span><span class="n">array</span><span class="p">(</span><span class="s1">&#39;d&#39;</span><span class="p">,</span> <span class="p">[</span><span class="mf">1.1</span><span class="p">,</span> <span class="mf">2.2</span><span class="p">,</span> <span class="mf">3.3</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="nb">memoryview</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">tolist</span><span class="p">()</span>
<span class="go">[1.1, 2.2, 3.3]</span>
</pre></div>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.3 版更改: </span><a class="reference internal" href="#memoryview.tolist" title="memoryview.tolist"><code class="xref py py-meth docutils literal notranslate"><span class="pre">tolist()</span></code></a> 现在支持 <a class="reference internal" href="struct.html#module-struct" title="struct: Interpret bytes as packed binary data."><code class="xref py py-mod docutils literal notranslate"><span class="pre">struct</span></code></a> 模块语法中的所有单字符原生格式以及多维表示形式。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="memoryview.release">
<code class="sig-name descname">release</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#memoryview.release" title="永久链接至目标">¶</a></dt>
<dd><p>释放由内存视图对象所公开的底层缓冲区。 许多对象在被视图所获取时都会采取特殊动作（例如，<a class="reference internal" href="#bytearray" title="bytearray"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytearray</span></code></a> 将会暂时禁止调整大小）；因此，调用 release() 可以方便地尽早去除这些限制（并释放任何多余的资源）。</p>
<p>在此方法被调用后，任何对视图的进一步操作将引发 <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><code class="xref py py-class docutils literal notranslate"><span class="pre">ValueError</span></code></a> (<a class="reference internal" href="#memoryview.release" title="memoryview.release"><code class="xref py py-meth docutils literal notranslate"><span class="pre">release()</span></code></a> 本身除外，它可以被多次调用):</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="nb">memoryview</span><span class="p">(</span><span class="sa">b</span><span class="s1">&#39;abc&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">release</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">ValueError</span>: <span class="n">operation forbidden on released memoryview object</span>
</pre></div>
</div>
<p>使用 <code class="docutils literal notranslate"><span class="pre">with</span></code> 语句，可以通过上下文管理协议达到类似的效果:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">with</span> <span class="nb">memoryview</span><span class="p">(</span><span class="sa">b</span><span class="s1">&#39;abc&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">m</span><span class="p">:</span>
<span class="gp">... </span>    <span class="n">m</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
<span class="gp">...</span>
<span class="go">97</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">ValueError</span>: <span class="n">operation forbidden on released memoryview object</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified added">3.2 新版功能.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="memoryview.cast">
<code class="sig-name descname">cast</code><span class="sig-paren">(</span><em class="sig-param">format</em><span class="optional">[</span>, <em class="sig-param">shape</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#memoryview.cast" title="永久链接至目标">¶</a></dt>
<dd><p>将内存视图转化为新的格式或形状。 <em>shape</em> 默认为 <code class="docutils literal notranslate"><span class="pre">[byte_length//new_itemsize]</span></code>，这意味着结果视图将是一维的。 返回值是一个新的内存视图，但缓冲区本身不会被复制。 支持的转化有 1D -&gt; C-<a class="reference internal" href="../glossary.html#term-contiguous"><span class="xref std std-term">contiguous</span></a> 和 C-contiguous -&gt; 1D。</p>
<p>目标格式仅限于 <a class="reference internal" href="struct.html#module-struct" title="struct: Interpret bytes as packed binary data."><code class="xref py py-mod docutils literal notranslate"><span class="pre">struct</span></code></a> 语法中的单一元素原生格式。 其中一种格式必须为字节格式 ('B', 'b' 或 'c')。 结果的字节长度必须与原始长度相同。</p>
<p>将 1D/long 转换为 1D/unsigned bytes:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">array</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="n">array</span><span class="o">.</span><span class="n">array</span><span class="p">(</span><span class="s1">&#39;l&#39;</span><span class="p">,</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="nb">memoryview</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span><span class="o">.</span><span class="n">format</span>
<span class="go">&#39;l&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span><span class="o">.</span><span class="n">itemsize</span>
<span class="go">8</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
<span class="go">3</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span><span class="o">.</span><span class="n">nbytes</span>
<span class="go">24</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span> <span class="o">=</span> <span class="n">x</span><span class="o">.</span><span class="n">cast</span><span class="p">(</span><span class="s1">&#39;B&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span><span class="o">.</span><span class="n">format</span>
<span class="go">&#39;B&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span><span class="o">.</span><span class="n">itemsize</span>
<span class="go">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">y</span><span class="p">)</span>
<span class="go">24</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span><span class="o">.</span><span class="n">nbytes</span>
<span class="go">24</span>
</pre></div>
</div>
<p>将 1D/unsigned bytes 转换为 1D/char:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="nb">bytearray</span><span class="p">(</span><span class="sa">b</span><span class="s1">&#39;zyz&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="nb">memoryview</span><span class="p">(</span><span class="n">b</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="sa">b</span><span class="s1">&#39;a&#39;</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">ValueError</span>: <span class="n">memoryview: invalid value for format &quot;B&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span> <span class="o">=</span> <span class="n">x</span><span class="o">.</span><span class="n">cast</span><span class="p">(</span><span class="s1">&#39;c&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="sa">b</span><span class="s1">&#39;a&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span>
<span class="go">bytearray(b&#39;ayz&#39;)</span>
</pre></div>
</div>
<p>将 1D/bytes 转换为 3D/ints 再转换为 1D/signed char:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">struct</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">buf</span> <span class="o">=</span> <span class="n">struct</span><span class="o">.</span><span class="n">pack</span><span class="p">(</span><span class="s2">&quot;i&quot;</span><span class="o">*</span><span class="mi">12</span><span class="p">,</span> <span class="o">*</span><span class="nb">list</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">12</span><span class="p">)))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="nb">memoryview</span><span class="p">(</span><span class="n">buf</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span> <span class="o">=</span> <span class="n">x</span><span class="o">.</span><span class="n">cast</span><span class="p">(</span><span class="s1">&#39;i&#39;</span><span class="p">,</span> <span class="n">shape</span><span class="o">=</span><span class="p">[</span><span class="mi">2</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span><span class="o">.</span><span class="n">tolist</span><span class="p">()</span>
<span class="go">[[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span><span class="o">.</span><span class="n">format</span>
<span class="go">&#39;i&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span><span class="o">.</span><span class="n">itemsize</span>
<span class="go">4</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">y</span><span class="p">)</span>
<span class="go">2</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span><span class="o">.</span><span class="n">nbytes</span>
<span class="go">48</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">z</span> <span class="o">=</span> <span class="n">y</span><span class="o">.</span><span class="n">cast</span><span class="p">(</span><span class="s1">&#39;b&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">z</span><span class="o">.</span><span class="n">format</span>
<span class="go">&#39;b&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">z</span><span class="o">.</span><span class="n">itemsize</span>
<span class="go">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">z</span><span class="p">)</span>
<span class="go">48</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">z</span><span class="o">.</span><span class="n">nbytes</span>
<span class="go">48</span>
</pre></div>
</div>
<p>将 1D/unsigned long 转换为 2D/unsigned long:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">buf</span> <span class="o">=</span> <span class="n">struct</span><span class="o">.</span><span class="n">pack</span><span class="p">(</span><span class="s2">&quot;L&quot;</span><span class="o">*</span><span class="mi">6</span><span class="p">,</span> <span class="o">*</span><span class="nb">list</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">6</span><span class="p">)))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="nb">memoryview</span><span class="p">(</span><span class="n">buf</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span> <span class="o">=</span> <span class="n">x</span><span class="o">.</span><span class="n">cast</span><span class="p">(</span><span class="s1">&#39;L&#39;</span><span class="p">,</span> <span class="n">shape</span><span class="o">=</span><span class="p">[</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">y</span><span class="p">)</span>
<span class="go">2</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span><span class="o">.</span><span class="n">nbytes</span>
<span class="go">48</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span><span class="o">.</span><span class="n">tolist</span><span class="p">()</span>
<span class="go">[[0, 1, 2], [3, 4, 5]]</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified added">3.3 新版功能.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.5 版更改: </span>当转换为字节视图时，源格式将不再受限。</p>
</div>
</dd></dl>

<p>还存在一些可用的只读属性：</p>
<dl class="attribute">
<dt id="memoryview.obj">
<code class="sig-name descname">obj</code><a class="headerlink" href="#memoryview.obj" title="永久链接至目标">¶</a></dt>
<dd><p>内存视图的下层对象:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">b</span>  <span class="o">=</span> <span class="nb">bytearray</span><span class="p">(</span><span class="sa">b</span><span class="s1">&#39;xyz&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="nb">memoryview</span><span class="p">(</span><span class="n">b</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">obj</span> <span class="ow">is</span> <span class="n">b</span>
<span class="go">True</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified added">3.3 新版功能.</span></p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="memoryview.nbytes">
<code class="sig-name descname">nbytes</code><a class="headerlink" href="#memoryview.nbytes" title="永久链接至目标">¶</a></dt>
<dd><p><code class="docutils literal notranslate"><span class="pre">nbytes</span> <span class="pre">==</span> <span class="pre">product(shape)</span> <span class="pre">*</span> <span class="pre">itemsize</span> <span class="pre">==</span> <span class="pre">len(m.tobytes())</span></code>。 这是数组在连续表示时将会占用的空间总字节数。 它不一定等于 <code class="docutils literal notranslate"><span class="pre">len(m)</span></code>:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">array</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="n">array</span><span class="o">.</span><span class="n">array</span><span class="p">(</span><span class="s1">&#39;i&#39;</span><span class="p">,</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">4</span><span class="p">,</span><span class="mi">5</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="nb">memoryview</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">m</span><span class="p">)</span>
<span class="go">5</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">nbytes</span>
<span class="go">20</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span> <span class="o">=</span> <span class="n">m</span><span class="p">[::</span><span class="mi">2</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">y</span><span class="p">)</span>
<span class="go">3</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span><span class="o">.</span><span class="n">nbytes</span>
<span class="go">12</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">y</span><span class="o">.</span><span class="n">tobytes</span><span class="p">())</span>
<span class="go">12</span>
</pre></div>
</div>
<p>多维数组:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">struct</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">buf</span> <span class="o">=</span> <span class="n">struct</span><span class="o">.</span><span class="n">pack</span><span class="p">(</span><span class="s2">&quot;d&quot;</span><span class="o">*</span><span class="mi">12</span><span class="p">,</span> <span class="o">*</span><span class="p">[</span><span class="mf">1.5</span><span class="o">*</span><span class="n">x</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">12</span><span class="p">)])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="nb">memoryview</span><span class="p">(</span><span class="n">buf</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span> <span class="o">=</span> <span class="n">x</span><span class="o">.</span><span class="n">cast</span><span class="p">(</span><span class="s1">&#39;d&#39;</span><span class="p">,</span> <span class="n">shape</span><span class="o">=</span><span class="p">[</span><span class="mi">3</span><span class="p">,</span><span class="mi">4</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span><span class="o">.</span><span class="n">tolist</span><span class="p">()</span>
<span class="go">[[0.0, 1.5, 3.0, 4.5], [6.0, 7.5, 9.0, 10.5], [12.0, 13.5, 15.0, 16.5]]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">y</span><span class="p">)</span>
<span class="go">3</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span><span class="o">.</span><span class="n">nbytes</span>
<span class="go">96</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified added">3.3 新版功能.</span></p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="memoryview.readonly">
<code class="sig-name descname">readonly</code><a class="headerlink" href="#memoryview.readonly" title="永久链接至目标">¶</a></dt>
<dd><p>一个表明内存是否只读的布尔值。</p>
</dd></dl>

<dl class="attribute">
<dt id="memoryview.format">
<code class="sig-name descname">format</code><a class="headerlink" href="#memoryview.format" title="永久链接至目标">¶</a></dt>
<dd><p>一个字符串，包含视图中每个元素的格式（表示为 <a class="reference internal" href="struct.html#module-struct" title="struct: Interpret bytes as packed binary data."><code class="xref py py-mod docutils literal notranslate"><span class="pre">struct</span></code></a> 模块样式）。 内存视图可以从具有任意格式字符串的导出器创建，但某些方法 (例如 <a class="reference internal" href="#memoryview.tolist" title="memoryview.tolist"><code class="xref py py-meth docutils literal notranslate"><span class="pre">tolist()</span></code></a>) 仅限于原生的单元素格式。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.3 版更改: </span>格式 <code class="docutils literal notranslate"><span class="pre">'B'</span></code> 现在会按照 struct 模块语法来处理。 这意味着 <code class="docutils literal notranslate"><span class="pre">memoryview(b'abc')[0]</span> <span class="pre">==</span> <span class="pre">b'abc'[0]</span> <span class="pre">==</span> <span class="pre">97</span></code>。</p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="memoryview.itemsize">
<code class="sig-name descname">itemsize</code><a class="headerlink" href="#memoryview.itemsize" title="永久链接至目标">¶</a></dt>
<dd><p>memoryview 中每个元素以字节表示的大小:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">array</span><span class="o">,</span> <span class="nn">struct</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="nb">memoryview</span><span class="p">(</span><span class="n">array</span><span class="o">.</span><span class="n">array</span><span class="p">(</span><span class="s1">&#39;H&#39;</span><span class="p">,</span> <span class="p">[</span><span class="mi">32000</span><span class="p">,</span> <span class="mi">32001</span><span class="p">,</span> <span class="mi">32002</span><span class="p">]))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">itemsize</span>
<span class="go">2</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
<span class="go">32000</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">struct</span><span class="o">.</span><span class="n">calcsize</span><span class="p">(</span><span class="s1">&#39;H&#39;</span><span class="p">)</span> <span class="o">==</span> <span class="n">m</span><span class="o">.</span><span class="n">itemsize</span>
<span class="go">True</span>
</pre></div>
</div>
</dd></dl>

<dl class="attribute">
<dt id="memoryview.ndim">
<code class="sig-name descname">ndim</code><a class="headerlink" href="#memoryview.ndim" title="永久链接至目标">¶</a></dt>
<dd><p>一个整数，表示内存所代表的多维数组具有多少个维度。</p>
</dd></dl>

<dl class="attribute">
<dt id="memoryview.shape">
<code class="sig-name descname">shape</code><a class="headerlink" href="#memoryview.shape" title="永久链接至目标">¶</a></dt>
<dd><p>一个整数元组，通过 <a class="reference internal" href="#memoryview.ndim" title="memoryview.ndim"><code class="xref py py-attr docutils literal notranslate"><span class="pre">ndim</span></code></a> 的长度值给出内存所代表的 N 维数组的形状。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.3 版更改: </span>当 ndim = 0 时值为空元组而不再为 <code class="docutils literal notranslate"><span class="pre">None</span></code>。</p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="memoryview.strides">
<code class="sig-name descname">strides</code><a class="headerlink" href="#memoryview.strides" title="永久链接至目标">¶</a></dt>
<dd><p>一个整数元组，通过 <a class="reference internal" href="#memoryview.ndim" title="memoryview.ndim"><code class="xref py py-attr docutils literal notranslate"><span class="pre">ndim</span></code></a> 的长度给出以字节表示的大小，以便访问数组中每个维度上的每个元素。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.3 版更改: </span>当 ndim = 0 时值为空元组而不再为 <code class="docutils literal notranslate"><span class="pre">None</span></code>。</p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="memoryview.suboffsets">
<code class="sig-name descname">suboffsets</code><a class="headerlink" href="#memoryview.suboffsets" title="永久链接至目标">¶</a></dt>
<dd><p>供 PIL 风格的数组内部使用。 该值仅作为参考信息。</p>
</dd></dl>

<dl class="attribute">
<dt id="memoryview.c_contiguous">
<code class="sig-name descname">c_contiguous</code><a class="headerlink" href="#memoryview.c_contiguous" title="永久链接至目标">¶</a></dt>
<dd><p>一个表明内存是否为 C-<a class="reference internal" href="../glossary.html#term-contiguous"><span class="xref std std-term">contiguous</span></a> 的布尔值。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.3 新版功能.</span></p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="memoryview.f_contiguous">
<code class="sig-name descname">f_contiguous</code><a class="headerlink" href="#memoryview.f_contiguous" title="永久链接至目标">¶</a></dt>
<dd><p>一个表明内存是否为 Fortran <a class="reference internal" href="../glossary.html#term-contiguous"><span class="xref std std-term">contiguous</span></a> 的布尔值。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.3 新版功能.</span></p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="memoryview.contiguous">
<code class="sig-name descname">contiguous</code><a class="headerlink" href="#memoryview.contiguous" title="永久链接至目标">¶</a></dt>
<dd><p>一个表明内存是否为 <a class="reference internal" href="../glossary.html#term-contiguous"><span class="xref std std-term">contiguous</span></a> 的布尔值。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.3 新版功能.</span></p>
</div>
</dd></dl>

</dd></dl>

</div>
</div>
<div class="section" id="set-types-set-frozenset">
<span id="types-set"></span><h2>集合类型 --- <a class="reference internal" href="#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a>, <a class="reference internal" href="#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a><a class="headerlink" href="#set-types-set-frozenset" title="永久链接至标题">¶</a></h2>
<p id="index-49"><em class="dfn">set</em> 对象是由具有唯一性的 <a class="reference internal" href="../glossary.html#term-hashable"><span class="xref std std-term">hashable</span></a> 对象所组成的无序多项集。 常见的用途包括成员检测、从序列中去除重复项以及数学中的集合类计算，例如交集、并集、差集与对称差集等等。 （关于其他容器对象请参看 <a class="reference internal" href="#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>, <a class="reference internal" href="#list" title="list"><code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code></a> 与 <a class="reference internal" href="#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a> 等内置类，以及 <a class="reference internal" href="collections.html#module-collections" title="collections: Container datatypes"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code></a> 模块。）</p>
<p>与其他多项集一样，集合也支持 <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">in</span> <span class="pre">set</span></code>, <code class="docutils literal notranslate"><span class="pre">len(set)</span></code> 和 <code class="docutils literal notranslate"><span class="pre">for</span> <span class="pre">x</span> <span class="pre">in</span> <span class="pre">set</span></code>。 作为一种无序的多项集，集合并不记录元素位置或插入顺序。 相应地，集合不支持索引、切片或其他序列类的操作。</p>
<p>目前有两种内置集合类型，<a class="reference internal" href="#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> 和 <a class="reference internal" href="#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a>。 <a class="reference internal" href="#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> 类型是可变的 --- 其内容可以使用 <code class="xref py py-meth docutils literal notranslate"><span class="pre">add()</span></code> 和 <code class="xref py py-meth docutils literal notranslate"><span class="pre">remove()</span></code> 这样的方法来改变。 由于是可变类型，它没有哈希值，且不能被用作字典的键或其他集合的元素。 <a class="reference internal" href="#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a> 类型是不可变并且为 <a class="reference internal" href="../glossary.html#term-hashable"><span class="xref std std-term">hashable</span></a> --- 其内容在被创建后不能再改变；因此它可以被用作字典的键或其他集合的元素。</p>
<p>除了可以使用 <a class="reference internal" href="#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> 构造器，非空的 set (不是 frozenset) 还可以通过将以逗号分隔的元素列表包含于花括号之内来创建，例如: <code class="docutils literal notranslate"><span class="pre">{'jack',</span> <span class="pre">'sjoerd'}</span></code>。</p>
<p>两个类的构造器具有相同的作用方式：</p>
<dl class="class">
<dt id="set">
<em class="property">class </em><code class="sig-name descname">set</code><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param">iterable</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#set" title="永久链接至目标">¶</a></dt>
<dt id="frozenset">
<em class="property">class </em><code class="sig-name descname">frozenset</code><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param">iterable</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#frozenset" title="永久链接至目标">¶</a></dt>
<dd><p>返回一个新的 set 或 frozenset 对象，其元素来自于 <em>iterable</em>。 集合的元素必须为 <a class="reference internal" href="../glossary.html#term-hashable"><span class="xref std std-term">hashable</span></a>。 要表示由集合对象构成的集合，所有的内层集合必须为 <a class="reference internal" href="#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a> 对象。 如果未指定 <em>iterable</em>，则将返回一个新的空集合。</p>
<p><a class="reference internal" href="#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> 和 <a class="reference internal" href="#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a> 的实例提供以下操作：</p>
<dl class="describe">
<dt>
<code class="sig-name descname">len(s)</code></dt>
<dd><p>返回集合 <em>s</em> 中的元素数量（即 <em>s</em> 的基数）。</p>
</dd></dl>

<dl class="describe">
<dt>
<code class="sig-name descname">x in s</code></dt>
<dd><p>检测 <em>x</em> 是否为 <em>s</em> 中的成员。</p>
</dd></dl>

<dl class="describe">
<dt>
<code class="sig-name descname">x not in s</code></dt>
<dd><p>检测 <em>x</em> 是否非 <em>s</em> 中的成员。</p>
</dd></dl>

<dl class="method">
<dt id="frozenset.isdisjoint">
<code class="sig-name descname">isdisjoint</code><span class="sig-paren">(</span><em class="sig-param">other</em><span class="sig-paren">)</span><a class="headerlink" href="#frozenset.isdisjoint" title="永久链接至目标">¶</a></dt>
<dd><p>如果集合中没有与 <em>other</em> 共有的元素则返回 <code class="docutils literal notranslate"><span class="pre">True</span></code>。 当且仅当两个集合的交集为空集合时，两者为不相交集合。</p>
</dd></dl>

<dl class="method">
<dt id="frozenset.issubset">
<code class="sig-name descname">issubset</code><span class="sig-paren">(</span><em class="sig-param">other</em><span class="sig-paren">)</span><a class="headerlink" href="#frozenset.issubset" title="永久链接至目标">¶</a></dt>
<dt>
<code class="sig-name descname">set &lt;= other</code></dt>
<dd><p>检测是否集合中的每个元素都在 <em>other</em> 之中。</p>
</dd></dl>

<dl class="method">
<dt>
<code class="sig-name descname">set &lt; other</code></dt>
<dd><p>检测集合是否为 <em>other</em> 的真子集，即 <code class="docutils literal notranslate"><span class="pre">set</span> <span class="pre">&lt;=</span> <span class="pre">other</span> <span class="pre">and</span> <span class="pre">set</span> <span class="pre">!=</span> <span class="pre">other</span></code>。</p>
</dd></dl>

<dl class="method">
<dt id="frozenset.issuperset">
<code class="sig-name descname">issuperset</code><span class="sig-paren">(</span><em class="sig-param">other</em><span class="sig-paren">)</span><a class="headerlink" href="#frozenset.issuperset" title="永久链接至目标">¶</a></dt>
<dt>
<code class="sig-name descname">set &gt;= other</code></dt>
<dd><p>检测是否 <em>other</em> 中的每个元素都在集合之中。</p>
</dd></dl>

<dl class="method">
<dt>
<code class="sig-name descname">set &gt; other</code></dt>
<dd><p>检测集合是否为 <em>other</em> 的真超集，即 <code class="docutils literal notranslate"><span class="pre">set</span> <span class="pre">&gt;=</span> <span class="pre">other</span> <span class="pre">and</span> <span class="pre">set</span> <span class="pre">!=</span> <span class="pre">other</span></code>。</p>
</dd></dl>

<dl class="method">
<dt id="frozenset.union">
<code class="sig-name descname">union</code><span class="sig-paren">(</span><em class="sig-param">*others</em><span class="sig-paren">)</span><a class="headerlink" href="#frozenset.union" title="永久链接至目标">¶</a></dt>
<dt>
<code class="sig-name descname">set | other | ...</code></dt>
<dd><p>返回一个新集合，其中包含来自原集合以及 others 指定的所有集合中的元素。</p>
</dd></dl>

<dl class="method">
<dt id="frozenset.intersection">
<code class="sig-name descname">intersection</code><span class="sig-paren">(</span><em class="sig-param">*others</em><span class="sig-paren">)</span><a class="headerlink" href="#frozenset.intersection" title="永久链接至目标">¶</a></dt>
<dt>
<code class="sig-name descname">set &amp; other &amp; ...</code></dt>
<dd><p>返回一个新集合，其中包含原集合以及 others 指定的所有集合中共有的元素。</p>
</dd></dl>

<dl class="method">
<dt id="frozenset.difference">
<code class="sig-name descname">difference</code><span class="sig-paren">(</span><em class="sig-param">*others</em><span class="sig-paren">)</span><a class="headerlink" href="#frozenset.difference" title="永久链接至目标">¶</a></dt>
<dt>
<code class="sig-name descname">set - other - ...</code></dt>
<dd><p>返回一个新集合，其中包含原集合中在 others 指定的其他集合中不存在的元素。</p>
</dd></dl>

<dl class="method">
<dt id="frozenset.symmetric_difference">
<code class="sig-name descname">symmetric_difference</code><span class="sig-paren">(</span><em class="sig-param">other</em><span class="sig-paren">)</span><a class="headerlink" href="#frozenset.symmetric_difference" title="永久链接至目标">¶</a></dt>
<dt>
<code class="sig-name descname">set ^ other</code></dt>
<dd><p>返回一个新集合，其中的元素或属于原集合或属于 <em>other</em> 指定的其他集合，但不能同时属于两者。</p>
</dd></dl>

<dl class="method">
<dt id="frozenset.copy">
<code class="sig-name descname">copy</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#frozenset.copy" title="永久链接至目标">¶</a></dt>
<dd><p>返回原集合的浅拷贝。</p>
</dd></dl>

<p>请注意，非运算符版本的 <a class="reference internal" href="#frozenset.union" title="frozenset.union"><code class="xref py py-meth docutils literal notranslate"><span class="pre">union()</span></code></a>, <a class="reference internal" href="#frozenset.intersection" title="frozenset.intersection"><code class="xref py py-meth docutils literal notranslate"><span class="pre">intersection()</span></code></a>, <a class="reference internal" href="#frozenset.difference" title="frozenset.difference"><code class="xref py py-meth docutils literal notranslate"><span class="pre">difference()</span></code></a>，以及 <a class="reference internal" href="#frozenset.symmetric_difference" title="frozenset.symmetric_difference"><code class="xref py py-meth docutils literal notranslate"><span class="pre">symmetric_difference()</span></code></a>, <a class="reference internal" href="#frozenset.issubset" title="frozenset.issubset"><code class="xref py py-meth docutils literal notranslate"><span class="pre">issubset()</span></code></a> 和 <a class="reference internal" href="#frozenset.issuperset" title="frozenset.issuperset"><code class="xref py py-meth docutils literal notranslate"><span class="pre">issuperset()</span></code></a> 方法会接受任意可迭代对象作为参数。 相比之下，它们所对应的运算符版本则要求其参数为集合。 这就排除了容易出错的构造形式例如 <code class="docutils literal notranslate"><span class="pre">set('abc')</span> <span class="pre">&amp;</span> <span class="pre">'cbs'</span></code>，而推荐可读性更强的 <code class="docutils literal notranslate"><span class="pre">set('abc').intersection('cbs')</span></code>。</p>
<p><a class="reference internal" href="#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> 和 <a class="reference internal" href="#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a> 均支持集合与集合的比较。 两个集合当且仅当每个集合中的每个元素均包含于另一个集合之内（即各为对方的子集）时则相等。 一个集合当且仅当其为另一个集合的真子集（即为后者的子集但两者不相等）时则小于另一个集合。 一个集合当且仅当其为另一个集合的真超集（即为后者的超集但两者不相等）时则大于另一个集合。</p>
<p><a class="reference internal" href="#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> 的实例与 <a class="reference internal" href="#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a> 的实例之间基于它们的成员进行比较。 例如 <code class="docutils literal notranslate"><span class="pre">set('abc')</span> <span class="pre">==</span> <span class="pre">frozenset('abc')</span></code> 返回 <code class="docutils literal notranslate"><span class="pre">True</span></code>，<code class="docutils literal notranslate"><span class="pre">set('abc')</span> <span class="pre">in</span> <span class="pre">set([frozenset('abc')])</span></code> 也一样。</p>
<p>子集与相等比较并不能推广为完全排序函数。 例如，任意两个非空且不相交的集合不相等且互不为对方的子集，因此以下 <em>所有</em> 比较均返回 <code class="docutils literal notranslate"><span class="pre">False</span></code>: <code class="docutils literal notranslate"><span class="pre">a&lt;b</span></code>, <code class="docutils literal notranslate"><span class="pre">a==b</span></code>, or <code class="docutils literal notranslate"><span class="pre">a&gt;b</span></code>。</p>
<p>由于集合仅定义了部分排序（子集关系），因此由集合构成的列表 <a class="reference internal" href="#list.sort" title="list.sort"><code class="xref py py-meth docutils literal notranslate"><span class="pre">list.sort()</span></code></a> 方法的输出并无定义。</p>
<p>集合的元素，与字典的键类似，必须为 <a class="reference internal" href="../glossary.html#term-hashable"><span class="xref std std-term">hashable</span></a>。</p>
<p>混合了 <a class="reference internal" href="#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> 实例与 <a class="reference internal" href="#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a> 的二进制位运算将返回与第一个操作数相同的类型。例如: <code class="docutils literal notranslate"><span class="pre">frozenset('ab')</span> <span class="pre">|</span> <span class="pre">set('bc')</span></code> 将返回 <a class="reference internal" href="#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a> 的实例。</p>
<p>下表列出了可用于 <a class="reference internal" href="#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> 而不能用于不可变的 <a class="reference internal" href="#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a> 实例的操作：</p>
<dl class="method">
<dt id="frozenset.update">
<code class="sig-name descname">update</code><span class="sig-paren">(</span><em class="sig-param">*others</em><span class="sig-paren">)</span><a class="headerlink" href="#frozenset.update" title="永久链接至目标">¶</a></dt>
<dt>
<code class="sig-name descname">set |= other | ...</code></dt>
<dd><p>更新集合，添加来自 others 中的所有元素。</p>
</dd></dl>

<dl class="method">
<dt id="frozenset.intersection_update">
<code class="sig-name descname">intersection_update</code><span class="sig-paren">(</span><em class="sig-param">*others</em><span class="sig-paren">)</span><a class="headerlink" href="#frozenset.intersection_update" title="永久链接至目标">¶</a></dt>
<dt>
<code class="sig-name descname">set &amp;= other &amp; ...</code></dt>
<dd><p>更新集合，只保留其中在所有 others 中也存在的元素。</p>
</dd></dl>

<dl class="method">
<dt id="frozenset.difference_update">
<code class="sig-name descname">difference_update</code><span class="sig-paren">(</span><em class="sig-param">*others</em><span class="sig-paren">)</span><a class="headerlink" href="#frozenset.difference_update" title="永久链接至目标">¶</a></dt>
<dt>
<code class="sig-name descname">set -= other | ...</code></dt>
<dd><p>更新集合，移除其中也存在于 others 中的元素。</p>
</dd></dl>

<dl class="method">
<dt id="frozenset.symmetric_difference_update">
<code class="sig-name descname">symmetric_difference_update</code><span class="sig-paren">(</span><em class="sig-param">other</em><span class="sig-paren">)</span><a class="headerlink" href="#frozenset.symmetric_difference_update" title="永久链接至目标">¶</a></dt>
<dt>
<code class="sig-name descname">set ^= other</code></dt>
<dd><p>更新集合，只保留存在于集合的一方而非共同存在的元素。</p>
</dd></dl>

<dl class="method">
<dt id="frozenset.add">
<code class="sig-name descname">add</code><span class="sig-paren">(</span><em class="sig-param">elem</em><span class="sig-paren">)</span><a class="headerlink" href="#frozenset.add" title="永久链接至目标">¶</a></dt>
<dd><p>将元素 <em>elem</em> 添加到集合中。</p>
</dd></dl>

<dl class="method">
<dt id="frozenset.remove">
<code class="sig-name descname">remove</code><span class="sig-paren">(</span><em class="sig-param">elem</em><span class="sig-paren">)</span><a class="headerlink" href="#frozenset.remove" title="永久链接至目标">¶</a></dt>
<dd><p>从集合中移除元素 <em>elem</em>。 如果 <em>elem</em> 不存在于集合中则会引发 <a class="reference internal" href="exceptions.html#KeyError" title="KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a>。</p>
</dd></dl>

<dl class="method">
<dt id="frozenset.discard">
<code class="sig-name descname">discard</code><span class="sig-paren">(</span><em class="sig-param">elem</em><span class="sig-paren">)</span><a class="headerlink" href="#frozenset.discard" title="永久链接至目标">¶</a></dt>
<dd><p>如果元素 <em>elem</em> 存在于集合中则将其移除。</p>
</dd></dl>

<dl class="method">
<dt id="frozenset.pop">
<code class="sig-name descname">pop</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#frozenset.pop" title="永久链接至目标">¶</a></dt>
<dd><p>从集合中移除并返回任意一个元素。 如果集合为空则会引发 <a class="reference internal" href="exceptions.html#KeyError" title="KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a>。</p>
</dd></dl>

<dl class="method">
<dt id="frozenset.clear">
<code class="sig-name descname">clear</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#frozenset.clear" title="永久链接至目标">¶</a></dt>
<dd><p>从集合中移除所有元素。</p>
</dd></dl>

<p>请注意，非运算符版本的 <a class="reference internal" href="#frozenset.update" title="frozenset.update"><code class="xref py py-meth docutils literal notranslate"><span class="pre">update()</span></code></a>, <a class="reference internal" href="#frozenset.intersection_update" title="frozenset.intersection_update"><code class="xref py py-meth docutils literal notranslate"><span class="pre">intersection_update()</span></code></a>, <a class="reference internal" href="#frozenset.difference_update" title="frozenset.difference_update"><code class="xref py py-meth docutils literal notranslate"><span class="pre">difference_update()</span></code></a> 和 <a class="reference internal" href="#frozenset.symmetric_difference_update" title="frozenset.symmetric_difference_update"><code class="xref py py-meth docutils literal notranslate"><span class="pre">symmetric_difference_update()</span></code></a> 方法将接受任意可迭代对象作为参数。</p>
<p>请注意，<a class="reference internal" href="../reference/datamodel.html#object.__contains__" title="object.__contains__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__contains__()</span></code></a>, <a class="reference internal" href="#frozenset.remove" title="frozenset.remove"><code class="xref py py-meth docutils literal notranslate"><span class="pre">remove()</span></code></a> 和 <a class="reference internal" href="#frozenset.discard" title="frozenset.discard"><code class="xref py py-meth docutils literal notranslate"><span class="pre">discard()</span></code></a> 方法的 <em>elem</em> 参数可能是一个 set。 为支持对一个等价的 frozenset 进行搜索，会根据 <em>elem</em> 临时创建一个该类型对象。</p>
</dd></dl>

</div>
<div class="section" id="mapping-types-dict">
<span id="typesmapping"></span><h2>映射类型 --- <a class="reference internal" href="#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a><a class="headerlink" href="#mapping-types-dict" title="永久链接至标题">¶</a></h2>
<p id="index-50"><a class="reference internal" href="../glossary.html#term-mapping"><span class="xref std std-term">mapping</span></a> 对象会将 <a class="reference internal" href="../glossary.html#term-hashable"><span class="xref std std-term">hashable</span></a> 值映射到任意对象。 映射属于可变对象。 目前仅有一种标准映射类型 <em class="dfn">字典</em>。 （关于其他容器对象请参看 <a class="reference internal" href="#list" title="list"><code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code></a>, <a class="reference internal" href="#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> 与 <a class="reference internal" href="#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a> 等内置类，以及 <a class="reference internal" href="collections.html#module-collections" title="collections: Container datatypes"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code></a> 模块。）</p>
<p>字典的键 <em>几乎</em> 可以是任何值。 非 <a class="reference internal" href="../glossary.html#term-hashable"><span class="xref std std-term">hashable</span></a> 的值，即包含列表、字典或其他可变类型的值（此类对象基于值而非对象标识进行比较）不可用作键。 数字类型用作键时遵循数字比较的一般规则：如果两个数值相等 (例如 <code class="docutils literal notranslate"><span class="pre">1</span></code> 和 <code class="docutils literal notranslate"><span class="pre">1.0</span></code>) 则两者可以被用来索引同一字典条目。 （但是请注意，由于计算机对于浮点数存储的只是近似值，因此将其用作字典键是不明智的。）</p>
<p>字典可以通过将以逗号分隔的 <code class="docutils literal notranslate"><span class="pre">键:</span> <span class="pre">值</span></code> 对列表包含于花括号之内来创建，例如: <code class="docutils literal notranslate"><span class="pre">{'jack':</span> <span class="pre">4098,</span> <span class="pre">'sjoerd':</span> <span class="pre">4127}</span></code> 或 <code class="docutils literal notranslate"><span class="pre">{4098:</span> <span class="pre">'jack',</span> <span class="pre">4127:</span> <span class="pre">'sjoerd'}</span></code>，也可以通过 <a class="reference internal" href="#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> 构造器来创建。</p>
<dl class="class">
<dt id="dict">
<em class="property">class </em><code class="sig-name descname">dict</code><span class="sig-paren">(</span><em class="sig-param">**kwarg</em><span class="sig-paren">)</span><a class="headerlink" href="#dict" title="永久链接至目标">¶</a></dt>
<dt>
<em class="property">class </em><code class="sig-name descname">dict</code><span class="sig-paren">(</span><em class="sig-param">mapping</em>, <em class="sig-param">**kwarg</em><span class="sig-paren">)</span></dt>
<dt>
<em class="property">class </em><code class="sig-name descname">dict</code><span class="sig-paren">(</span><em class="sig-param">iterable</em>, <em class="sig-param">**kwarg</em><span class="sig-paren">)</span></dt>
<dd><p>返回一个新的字典，基于可选的位置参数和可能为空的关键字参数集来初始化。</p>
<p>如果没有给出位置参数，将创建一个空字典。 如果给出一个位置参数并且其属于映射对象，将创建一个具有与映射对象相同键值对的字典。 否则的话，位置参数必须为一个 <a class="reference internal" href="../glossary.html#term-iterable"><span class="xref std std-term">iterable</span></a> 对象。 该可迭代对象中的每一项本身必须为一个刚好包含两个元素的可迭代对象。 每一项中的第一个对象将成为新字典的一个键，第二个对象将成为其对应的值。 如果一个键出现一次以上，该键的最后一个值将成为其在新字典中对应的值。</p>
<p>如果给出了关键字参数，则关键字参数及其值会被加入到基于位置参数创建的字典。 如果要加入的键已存在，来自关键字参数的值将替代来自位置参数的值。</p>
<p>作为演示，以下示例返回的字典均等于 <code class="docutils literal notranslate"><span class="pre">{&quot;one&quot;:</span> <span class="pre">1,</span> <span class="pre">&quot;two&quot;:</span> <span class="pre">2,</span> <span class="pre">&quot;three&quot;:</span> <span class="pre">3}</span></code>:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">(</span><span class="n">one</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="n">two</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">three</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;one&#39;</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span> <span class="s1">&#39;two&#39;</span><span class="p">:</span> <span class="mi">2</span><span class="p">,</span> <span class="s1">&#39;three&#39;</span><span class="p">:</span> <span class="mi">3</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">(</span><span class="nb">zip</span><span class="p">([</span><span class="s1">&#39;one&#39;</span><span class="p">,</span> <span class="s1">&#39;two&#39;</span><span class="p">,</span> <span class="s1">&#39;three&#39;</span><span class="p">],</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">([(</span><span class="s1">&#39;two&#39;</span><span class="p">,</span> <span class="mi">2</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;one&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;three&#39;</span><span class="p">,</span> <span class="mi">3</span><span class="p">)])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">e</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">({</span><span class="s1">&#39;three&#39;</span><span class="p">:</span> <span class="mi">3</span><span class="p">,</span> <span class="s1">&#39;one&#39;</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span> <span class="s1">&#39;two&#39;</span><span class="p">:</span> <span class="mi">2</span><span class="p">})</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">==</span> <span class="n">b</span> <span class="o">==</span> <span class="n">c</span> <span class="o">==</span> <span class="n">d</span> <span class="o">==</span> <span class="n">e</span>
<span class="go">True</span>
</pre></div>
</div>
<p>像第一个例子那样提供关键字参数的方式只能使用有效的 Python 标识符作为键。 其他方式则可使用任何有效的键。</p>
<p>这些是字典所支持的操作（因而自定义的映射类型也应当支持）：</p>
<dl class="describe">
<dt>
<code class="sig-name descname">list(d)</code></dt>
<dd><p>返回字典 <em>d</em> 中使用的所有键的列表。</p>
</dd></dl>

<dl class="describe">
<dt>
<code class="sig-name descname">len(d)</code></dt>
<dd><p>返回字典 <em>d</em> 中的项数。</p>
</dd></dl>

<dl class="describe">
<dt>
<code class="sig-name descname">d[key]</code></dt>
<dd><p>返回 <em>d</em> 中以 <em>key</em> 为键的项。 如果映射中不存在 <em>key</em> 则会引发 <a class="reference internal" href="exceptions.html#KeyError" title="KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a>。</p>
<p id="index-51">如果字典的子类定义了方法 <a class="reference internal" href="../reference/datamodel.html#object.__missing__" title="object.__missing__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__missing__()</span></code></a> 并且 <em>key</em> 不存在，则 <code class="docutils literal notranslate"><span class="pre">d[key]</span></code> 操作将调用该方法并附带键 <em>key</em> 作为参数。 <code class="docutils literal notranslate"><span class="pre">d[key]</span></code> 随后将返回或引发 <code class="docutils literal notranslate"><span class="pre">__missing__(key)</span></code> 调用所返回或引发的任何对象或异常。 没有其他操作或方法会发起调用 <a class="reference internal" href="../reference/datamodel.html#object.__missing__" title="object.__missing__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__missing__()</span></code></a>。 如果未定义 <a class="reference internal" href="../reference/datamodel.html#object.__missing__" title="object.__missing__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__missing__()</span></code></a>，则会引发 <a class="reference internal" href="exceptions.html#KeyError" title="KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a>。 <a class="reference internal" href="../reference/datamodel.html#object.__missing__" title="object.__missing__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__missing__()</span></code></a> 必须是一个方法；它不能是一个实例变量:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">Counter</span><span class="p">(</span><span class="nb">dict</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="fm">__missing__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">):</span>
<span class="gp">... </span>        <span class="k">return</span> <span class="mi">0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="p">[</span><span class="s1">&#39;red&#39;</span><span class="p">]</span>
<span class="go">0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="p">[</span><span class="s1">&#39;red&#39;</span><span class="p">]</span> <span class="o">+=</span> <span class="mi">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="p">[</span><span class="s1">&#39;red&#39;</span><span class="p">]</span>
<span class="go">1</span>
</pre></div>
</div>
<p>上面的例子显示了 <a class="reference internal" href="collections.html#collections.Counter" title="collections.Counter"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.Counter</span></code></a> 实现的部分代码。 还有另一个不同的 <code class="docutils literal notranslate"><span class="pre">__missing__</span></code> 方法是由 <a class="reference internal" href="collections.html#collections.defaultdict" title="collections.defaultdict"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.defaultdict</span></code></a> 所使用的。</p>
</dd></dl>

<dl class="describe">
<dt>
<code class="sig-name descname">d[key] = value</code></dt>
<dd><p>将 <code class="docutils literal notranslate"><span class="pre">d[key]</span></code> 设为 <em>value</em>。</p>
</dd></dl>

<dl class="describe">
<dt>
<code class="sig-name descname">del d[key]</code></dt>
<dd><p>将 <code class="docutils literal notranslate"><span class="pre">d[key]</span></code> 从 <em>d</em> 中移除。 如果映射中不存在 <em>key</em> 则会引发 <a class="reference internal" href="exceptions.html#KeyError" title="KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a>。</p>
</dd></dl>

<dl class="describe">
<dt>
<code class="sig-name descname">key in d</code></dt>
<dd><p>如果 <em>d</em> 中存在键 <em>key</em> 则返回 <code class="docutils literal notranslate"><span class="pre">True</span></code>，否则返回 <code class="docutils literal notranslate"><span class="pre">False</span></code>。</p>
</dd></dl>

<dl class="describe">
<dt>
<code class="sig-name descname">key not in d</code></dt>
<dd><p>等价于 <code class="docutils literal notranslate"><span class="pre">not</span> <span class="pre">key</span> <span class="pre">in</span> <span class="pre">d</span></code>。</p>
</dd></dl>

<dl class="describe">
<dt>
<code class="sig-name descname">iter(d)</code></dt>
<dd><p>返回以字典的键为元素的迭代器。 这是 <code class="docutils literal notranslate"><span class="pre">iter(d.keys())</span></code> 的快捷方式。</p>
</dd></dl>

<dl class="method">
<dt id="dict.clear">
<code class="sig-name descname">clear</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#dict.clear" title="永久链接至目标">¶</a></dt>
<dd><p>移除字典中的所有元素。</p>
</dd></dl>

<dl class="method">
<dt id="dict.copy">
<code class="sig-name descname">copy</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#dict.copy" title="永久链接至目标">¶</a></dt>
<dd><p>返回原字典的浅拷贝。</p>
</dd></dl>

<dl class="method">
<dt id="dict.fromkeys">
<em class="property">classmethod </em><code class="sig-name descname">fromkeys</code><span class="sig-paren">(</span><em class="sig-param">iterable</em><span class="optional">[</span>, <em class="sig-param">value</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#dict.fromkeys" title="永久链接至目标">¶</a></dt>
<dd><p>使用来自 <em>iterable</em> 的键创建一个新字典，并将键值设为 <em>value</em>。</p>
<p><a class="reference internal" href="#dict.fromkeys" title="dict.fromkeys"><code class="xref py py-meth docutils literal notranslate"><span class="pre">fromkeys()</span></code></a> 属于类方法，会返回一个新字典。 <em>value</em> 默认为 <code class="docutils literal notranslate"><span class="pre">None</span></code>。</p>
</dd></dl>

<dl class="method">
<dt id="dict.get">
<code class="sig-name descname">get</code><span class="sig-paren">(</span><em class="sig-param">key</em><span class="optional">[</span>, <em class="sig-param">default</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#dict.get" title="永久链接至目标">¶</a></dt>
<dd><p>如果 <em>key</em> 存在于字典中则返回 <em>key</em> 的值，否则返回 <em>default</em>。 如果 <em>default</em> 未给出则默认为 <code class="docutils literal notranslate"><span class="pre">None</span></code>，因而此方法绝不会引发 <a class="reference internal" href="exceptions.html#KeyError" title="KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a>。</p>
</dd></dl>

<dl class="method">
<dt id="dict.items">
<code class="sig-name descname">items</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#dict.items" title="永久链接至目标">¶</a></dt>
<dd><p>返回由字典项 (<code class="docutils literal notranslate"><span class="pre">(键,</span> <span class="pre">值)</span></code> 对) 组成的一个新视图。 参见 <a class="reference internal" href="#dict-views"><span class="std std-ref">视图对象文档</span></a>。</p>
</dd></dl>

<dl class="method">
<dt id="dict.keys">
<code class="sig-name descname">keys</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#dict.keys" title="永久链接至目标">¶</a></dt>
<dd><p>返回由字典键组成的一个新视图。 参见 <a class="reference internal" href="#dict-views"><span class="std std-ref">视图对象文档</span></a>。</p>
</dd></dl>

<dl class="method">
<dt id="dict.pop">
<code class="sig-name descname">pop</code><span class="sig-paren">(</span><em class="sig-param">key</em><span class="optional">[</span>, <em class="sig-param">default</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#dict.pop" title="永久链接至目标">¶</a></dt>
<dd><p>如果 <em>key</em> 存在于字典中则将其移除并返回其值，否则返回 <em>default</em>。 如果 <em>default</em> 未给出且 <em>key</em> 不存在于字典中，则会引发 <a class="reference internal" href="exceptions.html#KeyError" title="KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a>。</p>
</dd></dl>

<dl class="method">
<dt id="dict.popitem">
<code class="sig-name descname">popitem</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#dict.popitem" title="永久链接至目标">¶</a></dt>
<dd><p>从字典中移除并返回一个 <code class="docutils literal notranslate"><span class="pre">(键,</span> <span class="pre">值)</span></code> 对。 键值对会按 <abbr title="后进先出">LIFO</abbr> 的顺序被返回。</p>
<p><a class="reference internal" href="#dict.popitem" title="dict.popitem"><code class="xref py py-meth docutils literal notranslate"><span class="pre">popitem()</span></code></a> 适用于对字典进行消耗性的迭代，这在集合算法中经常被使用。 如果字典为空，调用 <a class="reference internal" href="#dict.popitem" title="dict.popitem"><code class="xref py py-meth docutils literal notranslate"><span class="pre">popitem()</span></code></a> 将引发 <a class="reference internal" href="exceptions.html#KeyError" title="KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a>。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.7 版更改: </span>现在会确保采用 LIFO 顺序。 在之前的版本中，<a class="reference internal" href="#dict.popitem" title="dict.popitem"><code class="xref py py-meth docutils literal notranslate"><span class="pre">popitem()</span></code></a> 会返回一个任意的键/值对。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="dict.setdefault">
<code class="sig-name descname">setdefault</code><span class="sig-paren">(</span><em class="sig-param">key</em><span class="optional">[</span>, <em class="sig-param">default</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#dict.setdefault" title="永久链接至目标">¶</a></dt>
<dd><p>如果字典存在键 <em>key</em> ，返回它的值。如果不存在，插入值为 <em>default</em> 的键 <em>key</em> ，并返回 <em>default</em> 。 <em>default</em> 默认为 <code class="docutils literal notranslate"><span class="pre">None</span></code>。</p>
</dd></dl>

<dl class="method">
<dt id="dict.update">
<code class="sig-name descname">update</code><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param">other</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#dict.update" title="永久链接至目标">¶</a></dt>
<dd><p>使用来自 <em>other</em> 的键/值对更新字典，覆盖原有的键。 返回 <code class="docutils literal notranslate"><span class="pre">None</span></code>。</p>
<p><a class="reference internal" href="#dict.update" title="dict.update"><code class="xref py py-meth docutils literal notranslate"><span class="pre">update()</span></code></a> 接受另一个字典对象，或者一个包含键/值对（以长度为二的元组或其他可迭代对象表示）的可迭代对象。 如果给出了关键字参数，则会以其所指定的键/值对更新字典: <code class="docutils literal notranslate"><span class="pre">d.update(red=1,</span> <span class="pre">blue=2)</span></code>。</p>
</dd></dl>

<dl class="method">
<dt id="dict.values">
<code class="sig-name descname">values</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#dict.values" title="永久链接至目标">¶</a></dt>
<dd><p>返回由字典值组成的一个新视图。 参见 <a class="reference internal" href="#dict-views"><span class="std std-ref">视图对象文档</span></a>。</p>
<p>两个 <code class="docutils literal notranslate"><span class="pre">dict.values()</span></code> 视图之间的相等性比较将总是返回 <code class="docutils literal notranslate"><span class="pre">False</span></code>。 这在 <code class="docutils literal notranslate"><span class="pre">dict.values()</span></code> 与其自身比较时也同样适用:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;a&#39;</span><span class="p">:</span> <span class="mi">1</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">values</span><span class="p">()</span> <span class="o">==</span> <span class="n">d</span><span class="o">.</span><span class="n">values</span><span class="p">()</span>
<span class="go">False</span>
</pre></div>
</div>
</dd></dl>

<p>两个字典的比较当且仅当它们具有相同的 <code class="docutils literal notranslate"><span class="pre">(键,</span> <span class="pre">值)</span></code> 对时才会相等（不考虑顺序）。 排序比较 ('&lt;', '&lt;=', '&gt;=', '&gt;') 会引发 <a class="reference internal" href="exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>。</p>
<p>字典会保留插入时的顺序。 请注意对键的更新不会影响顺序。 删除并再次添加的键将被插入到末尾。</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="p">{</span><span class="s2">&quot;one&quot;</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span> <span class="s2">&quot;two&quot;</span><span class="p">:</span> <span class="mi">2</span><span class="p">,</span> <span class="s2">&quot;three&quot;</span><span class="p">:</span> <span class="mi">3</span><span class="p">,</span> <span class="s2">&quot;four&quot;</span><span class="p">:</span> <span class="mi">4</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span>
<span class="go">{&#39;one&#39;: 1, &#39;two&#39;: 2, &#39;three&#39;: 3, &#39;four&#39;: 4}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">d</span><span class="p">)</span>
<span class="go">[&#39;one&#39;, &#39;two&#39;, &#39;three&#39;, &#39;four&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">d</span><span class="o">.</span><span class="n">values</span><span class="p">())</span>
<span class="go">[1, 2, 3, 4]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="p">[</span><span class="s2">&quot;one&quot;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">42</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span>
<span class="go">{&#39;one&#39;: 42, &#39;two&#39;: 2, &#39;three&#39;: 3, &#39;four&#39;: 4}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">del</span> <span class="n">d</span><span class="p">[</span><span class="s2">&quot;two&quot;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="p">[</span><span class="s2">&quot;two&quot;</span><span class="p">]</span> <span class="o">=</span> <span class="kc">None</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span>
<span class="go">{&#39;one&#39;: 42, &#39;three&#39;: 3, &#39;four&#39;: 4, &#39;two&#39;: None}</span>
</pre></div>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.7 版更改: </span>字典顺序会确保为插入顺序。 此行为是自 3.6 版开始的 CPython 实现细节。</p>
</div>
</dd></dl>

<div class="admonition seealso">
<p class="admonition-title">参见</p>
<p><a class="reference internal" href="types.html#types.MappingProxyType" title="types.MappingProxyType"><code class="xref py py-class docutils literal notranslate"><span class="pre">types.MappingProxyType</span></code></a> 可被用来创建一个 <a class="reference internal" href="#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> 的只读视图。</p>
</div>
<div class="section" id="dictionary-view-objects">
<span id="dict-views"></span><h3>字典视图对象<a class="headerlink" href="#dictionary-view-objects" title="永久链接至标题">¶</a></h3>
<p>由 <a class="reference internal" href="#dict.keys" title="dict.keys"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.keys()</span></code></a>, <a class="reference internal" href="#dict.values" title="dict.values"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.values()</span></code></a> 和 <a class="reference internal" href="#dict.items" title="dict.items"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.items()</span></code></a> 所返回的对象是 <em>视图对象</em>。 该对象提供字典条目的一个动态视图，这意味着当字典改变时，视图也会相应改变。</p>
<p>字典视图可以被迭代以产生与其对应的数据，并支持成员检测：</p>
<dl class="describe">
<dt>
<code class="sig-name descname">len(dictview)</code></dt>
<dd><p>返回字典中的条目数。</p>
</dd></dl>

<dl class="describe">
<dt>
<code class="sig-name descname">iter(dictview)</code></dt>
<dd><p>返回字典中的键、值或项（以 <code class="docutils literal notranslate"><span class="pre">(键,</span> <span class="pre">值)</span></code> 为元素的元组表示）的迭代器。</p>
<p>键和值是按插入时的顺序进行迭代的。 这样就允许使用 <a class="reference internal" href="functions.html#zip" title="zip"><code class="xref py py-func docutils literal notranslate"><span class="pre">zip()</span></code></a> 来创建 <code class="docutils literal notranslate"><span class="pre">(值,</span> <span class="pre">键)</span></code> 对: <code class="docutils literal notranslate"><span class="pre">pairs</span> <span class="pre">=</span> <span class="pre">zip(d.values(),</span> <span class="pre">d.keys())</span></code>。 另一个创建相同列表的方式是 <code class="docutils literal notranslate"><span class="pre">pairs</span> <span class="pre">=</span> <span class="pre">[(v,</span> <span class="pre">k)</span> <span class="pre">for</span> <span class="pre">(k,</span> <span class="pre">v)</span> <span class="pre">in</span> <span class="pre">d.items()]</span></code>.</p>
<p>在添加或删除字典中的条目期间对视图进行迭代可能引发 <a class="reference internal" href="exceptions.html#RuntimeError" title="RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> 或者无法完全迭代所有条目。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.7 版更改: </span>字典顺序会确保为插入顺序。</p>
</div>
</dd></dl>

<dl class="describe">
<dt>
<code class="sig-name descname">x in dictview</code></dt>
<dd><p>如果 <em>x</em> 是对应字典中存在的键、值或项（在最后一种情况下 <em>x</em> 应为一个 <code class="docutils literal notranslate"><span class="pre">(键,</span> <span class="pre">值)</span></code> 元组） 则返回 <code class="docutils literal notranslate"><span class="pre">True</span></code>。</p>
</dd></dl>

<p>键视图类似于集合，因为其条目不重复且可哈希。 如果所有值都是可哈希的，即 <code class="docutils literal notranslate"><span class="pre">(键,</span> <span class="pre">值)</span></code> 对也是不重复且可哈希的，那么条目视图也会类似于集合。 （值视图则不被视为类似于集合，因其条目通常都是有重复的。） 对于类似于集合的视图，为抽象基类 <a class="reference internal" href="collections.abc.html#collections.abc.Set" title="collections.abc.Set"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.abc.Set</span></code></a> 所定义的全部操作都是有效的 (例如 <code class="docutils literal notranslate"><span class="pre">==</span></code>, <code class="docutils literal notranslate"><span class="pre">&lt;</span></code> 或 <code class="docutils literal notranslate"><span class="pre">^</span></code>)。</p>
<p>一个使用字典视图的示例:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">dishes</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;eggs&#39;</span><span class="p">:</span> <span class="mi">2</span><span class="p">,</span> <span class="s1">&#39;sausage&#39;</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span> <span class="s1">&#39;bacon&#39;</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span> <span class="s1">&#39;spam&#39;</span><span class="p">:</span> <span class="mi">500</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">keys</span> <span class="o">=</span> <span class="n">dishes</span><span class="o">.</span><span class="n">keys</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">values</span> <span class="o">=</span> <span class="n">dishes</span><span class="o">.</span><span class="n">values</span><span class="p">()</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># iteration</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">n</span> <span class="o">=</span> <span class="mi">0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">val</span> <span class="ow">in</span> <span class="n">values</span><span class="p">:</span>
<span class="gp">... </span>    <span class="n">n</span> <span class="o">+=</span> <span class="n">val</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">n</span><span class="p">)</span>
<span class="go">504</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># keys and values are iterated over in the same order (insertion order)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">keys</span><span class="p">)</span>
<span class="go">[&#39;eggs&#39;, &#39;sausage&#39;, &#39;bacon&#39;, &#39;spam&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">values</span><span class="p">)</span>
<span class="go">[2, 1, 1, 500]</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># view objects are dynamic and reflect dict changes</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">del</span> <span class="n">dishes</span><span class="p">[</span><span class="s1">&#39;eggs&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">del</span> <span class="n">dishes</span><span class="p">[</span><span class="s1">&#39;sausage&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">keys</span><span class="p">)</span>
<span class="go">[&#39;bacon&#39;, &#39;spam&#39;]</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># set operations</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">keys</span> <span class="o">&amp;</span> <span class="p">{</span><span class="s1">&#39;eggs&#39;</span><span class="p">,</span> <span class="s1">&#39;bacon&#39;</span><span class="p">,</span> <span class="s1">&#39;salad&#39;</span><span class="p">}</span>
<span class="go">{&#39;bacon&#39;}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">keys</span> <span class="o">^</span> <span class="p">{</span><span class="s1">&#39;sausage&#39;</span><span class="p">,</span> <span class="s1">&#39;juice&#39;</span><span class="p">}</span>
<span class="go">{&#39;juice&#39;, &#39;sausage&#39;, &#39;bacon&#39;, &#39;spam&#39;}</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="context-manager-types">
<span id="typecontextmanager"></span><h2>上下文管理器类型<a class="headerlink" href="#context-manager-types" title="永久链接至标题">¶</a></h2>
<p id="index-52">Python 的 <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> 语句支持通过上下文管理器所定义的运行时上下文这一概念。 此对象的实现使用了一对专门方法，允许用户自定义类来定义运行时上下文，在语句体被执行前进入该上下文，并在语句执行完毕时退出该上下文：</p>
<dl class="method">
<dt id="contextmanager.__enter__">
<code class="sig-prename descclassname">contextmanager.</code><code class="sig-name descname">__enter__</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#contextmanager.__enter__" title="永久链接至目标">¶</a></dt>
<dd><p>进入运行时上下文并返回此对象或关联到该运行时上下文的其他对象。 此方法的返回值会绑定到使用此上下文管理器的 <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> 语句的 <code class="xref std std-keyword docutils literal notranslate"><span class="pre">as</span></code> 子句中的标识符。</p>
<p>一个返回其自身的上下文管理器的例子是 <a class="reference internal" href="../glossary.html#term-file-object"><span class="xref std std-term">file object</span></a>。 文件对象会从 __enter__() 返回其自身，以允许 <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> 被用作 <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> 语句中的上下文表达式。</p>
<p>一个返回关联对象的上下文管理器的例子是 <a class="reference internal" href="decimal.html#decimal.localcontext" title="decimal.localcontext"><code class="xref py py-func docutils literal notranslate"><span class="pre">decimal.localcontext()</span></code></a> 所返回的对象。 此种管理器会将活动的 decimal 上下文设为原始 decimal 上下文的一个副本并返回该副本。 这允许对 <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> 语句的语句体中的当前 decimal 上下文进行更改，而不会影响 <code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code> 语句以外的代码。</p>
</dd></dl>

<dl class="method">
<dt id="contextmanager.__exit__">
<code class="sig-prename descclassname">contextmanager.</code><code class="sig-name descname">__exit__</code><span class="sig-paren">(</span><em class="sig-param">exc_type</em>, <em class="sig-param">exc_val</em>, <em class="sig-param">exc_tb</em><span class="sig-paren">)</span><a class="headerlink" href="#contextmanager.__exit__" title="永久链接至目标">¶</a></dt>
<dd><p>退出运行时上下文并返回一个布尔值旗标来表明所发生的任何异常是否应当被屏蔽。 如果在执行 <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> 语句的语句体期间发生了异常，则参数会包含异常的类型、值以及回溯信息。 在其他情况下三个参数均为 <code class="docutils literal notranslate"><span class="pre">None</span></code>。</p>
<p>自此方法返回一个真值将导致 <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> 语句屏蔽异常并继续执行紧随在 <code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code> 语句之后的语句。 否则异常将在此方法结束执行后继续传播。 在此方法执行期间发生的异常将会取代 <code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code> 语句的语句体中发生的任何异常。</p>
<p>传入的异常绝对不应当被显式地重新引发 —— 相反地，此方法应当返回一个假值以表明方法已成功完成并且不希望屏蔽被引发的异常。 这允许上下文管理代码方便地检测 <a class="reference internal" href="#contextmanager.__exit__" title="contextmanager.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> 方法是否确实已失败。</p>
</dd></dl>

<p>Python 定义了一些上下文管理器来支持简易的线程同步、文件或其他对象的快速关闭，以及更方便地操作活动的十进制算术上下文。 除了实现上下文管理协议以外，不同类型不会被特殊处理。 请参阅 <a class="reference internal" href="contextlib.html#module-contextlib" title="contextlib: Utilities for with-statement contexts."><code class="xref py py-mod docutils literal notranslate"><span class="pre">contextlib</span></code></a> 模块查看相关的示例。</p>
<p>Python 的 <a class="reference internal" href="../glossary.html#term-generator"><span class="xref std std-term">generator</span></a> 和 <a class="reference internal" href="contextlib.html#contextlib.contextmanager" title="contextlib.contextmanager"><code class="xref py py-class docutils literal notranslate"><span class="pre">contextlib.contextmanager</span></code></a> 装饰器提供了实现这些协议的便捷方式。 如果使用 <a class="reference internal" href="contextlib.html#contextlib.contextmanager" title="contextlib.contextmanager"><code class="xref py py-class docutils literal notranslate"><span class="pre">contextlib.contextmanager</span></code></a> 装饰器来装饰一个生成器函数，它将返回一个实现了必要的 <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> and <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> 方法的上下文管理器，而不再是由未经装饰的生成器函数所产生的迭代器。</p>
<p>请注意，Python/C API 中 Python 对象的类型结构中并没有针对这些方法的专门槽位。 想要定义这些方法的扩展类型必须将它们作为普通的 Python 可访问方法来提供。 与设置运行时上下文的开销相比，单个类字典查找的开销可以忽略不计。</p>
</div>
<div class="section" id="other-built-in-types">
<span id="typesother"></span><h2>其他内置类型<a class="headerlink" href="#other-built-in-types" title="永久链接至标题">¶</a></h2>
<p>解释器支持一些其他种类的对象。 这些对象大都仅支持一两种操作。</p>
<div class="section" id="modules">
<span id="typesmodules"></span><h3>模块<a class="headerlink" href="#modules" title="永久链接至标题">¶</a></h3>
<p>模块唯一的特殊操作是属性访问: <code class="docutils literal notranslate"><span class="pre">m.name</span></code>，这里 <em>m</em> 为一个模块而 <em>name</em> 访问定义在 <em>m</em> 的符号表中的一个名称。 模块属性可以被赋值。 （请注意 <a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> 语句严格来说也是对模块对象的一种操作；<code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">foo</span></code> 不要求存在一个名为 <em>foo</em> 的模块对象，而是要求存在一个对于名为 <em>foo</em> 的模块的 (永久性) <em>定义</em>。）</p>
<p>每个模块都有一个特殊属性 <a class="reference internal" href="#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a>。 这是包含模块的符号表的字典。 修改此字典将实际改变模块的符号表，但是无法直接对 <a class="reference internal" href="#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> 赋值 (你可以写 <code class="docutils literal notranslate"><span class="pre">m.__dict__['a']</span> <span class="pre">=</span> <span class="pre">1</span></code>，这会将 <code class="docutils literal notranslate"><span class="pre">m.a</span></code> 定义为 <code class="docutils literal notranslate"><span class="pre">1</span></code>，但是你不能写 <code class="docutils literal notranslate"><span class="pre">m.__dict__</span> <span class="pre">=</span> <span class="pre">{}</span></code>)。 不建议直接修改 <a class="reference internal" href="#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a>。</p>
<p>内置于解释器中的模块会写成这样: <code class="docutils literal notranslate"><span class="pre">&lt;module</span> <span class="pre">'sys'</span> <span class="pre">(built-in)&gt;</span></code>。 如果是从一个文件加载，则会写成 <code class="docutils literal notranslate"><span class="pre">&lt;module</span> <span class="pre">'os'</span> <span class="pre">from</span> <span class="pre">'/usr/local/lib/pythonX.Y/os.pyc'&gt;</span></code>。</p>
</div>
<div class="section" id="classes-and-class-instances">
<span id="typesobjects"></span><h3>类与类实例<a class="headerlink" href="#classes-and-class-instances" title="永久链接至标题">¶</a></h3>
<p>关于这些类型请参阅 <a class="reference internal" href="../reference/datamodel.html#objects"><span class="std std-ref">对象、值与类型</span></a> 和 <a class="reference internal" href="../reference/compound_stmts.html#class"><span class="std std-ref">类定义</span></a>。</p>
</div>
<div class="section" id="functions">
<span id="typesfunctions"></span><h3>函数<a class="headerlink" href="#functions" title="永久链接至标题">¶</a></h3>
<p>函数对象是通过函数定义创建的。 对函数对象的唯一操作是调用它: <code class="docutils literal notranslate"><span class="pre">func(argument-list)</span></code>。</p>
<p>实际上存在两种不同的函数对象：内置函数和用户自定义函数。 两者支持同样的操作（调用函数），但实现方式不同，因此对象类型也不同。</p>
<p>更多信息请参阅 <a class="reference internal" href="../reference/compound_stmts.html#function"><span class="std std-ref">函数定义</span></a>。</p>
</div>
<div class="section" id="methods">
<span id="typesmethods"></span><h3>方法<a class="headerlink" href="#methods" title="永久链接至标题">¶</a></h3>
<p id="index-53">方法是使用属性表示法来调用的函数。 存在两种形式：内置方法（例如列表的 <code class="xref py py-meth docutils literal notranslate"><span class="pre">append()</span></code> 方法）和类实例方法。 内置方法由支持它们的类型来描述。</p>
<p>如果你通过一个实例来访问方法（即定义在类命名空间内的函数），你会得到一个特殊对象: <em class="dfn">绑定方法</em> (或称 <em class="dfn">实例方法</em>) 对象。 当被调用时，它会将 <code class="docutils literal notranslate"><span class="pre">self</span></code> 参数添加到参数列表。 绑定方法具有两个特殊的只读属性: <code class="docutils literal notranslate"><span class="pre">m.__self__</span></code> 操作该方法的对象，而 <code class="docutils literal notranslate"><span class="pre">m.__func__</span></code> 是实现该方法的函数。 调用 <code class="docutils literal notranslate"><span class="pre">m(arg-1,</span> <span class="pre">arg-2,</span> <span class="pre">...,</span> <span class="pre">arg-n)</span></code> 完全等价于调用 <code class="docutils literal notranslate"><span class="pre">m.__func__(m.__self__,</span> <span class="pre">arg-1,</span> <span class="pre">arg-2,</span> <span class="pre">...,</span> <span class="pre">arg-n)</span></code>。</p>
<p>与函数对象类似，绑定方法对象也支持获取任意属性。 但是，由于方法属性实际上保存于下层的函数对象中 (<code class="docutils literal notranslate"><span class="pre">meth.__func__</span></code>)，因此不允许设置绑定方法的方法属性。 尝试设置方法的属性将会导致引发 <a class="reference internal" href="exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a>。 想要设置方法属性，你必须在下层的函数对象中显式地对其进行设置:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">C</span><span class="p">:</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">method</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="gp">... </span>        <span class="k">pass</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">C</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="n">method</span><span class="o">.</span><span class="n">whoami</span> <span class="o">=</span> <span class="s1">&#39;my name is method&#39;</span>  <span class="c1"># can&#39;t set on the method</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">AttributeError</span>: <span class="n">&#39;method&#39; object has no attribute &#39;whoami&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="n">method</span><span class="o">.</span><span class="vm">__func__</span><span class="o">.</span><span class="n">whoami</span> <span class="o">=</span> <span class="s1">&#39;my name is method&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="n">method</span><span class="o">.</span><span class="n">whoami</span>
<span class="go">&#39;my name is method&#39;</span>
</pre></div>
</div>
<p>更多信息请参阅 <a class="reference internal" href="../reference/datamodel.html#types"><span class="std std-ref">标准类型层级结构</span></a>。</p>
</div>
<div class="section" id="code-objects">
<span id="bltin-code-objects"></span><span id="index-54"></span><h3>代码对象<a class="headerlink" href="#code-objects" title="永久链接至标题">¶</a></h3>
<p id="index-55">代码对象被具体实现用来表示“伪编译”的可执行 Python 代码，例如一个函数体。 它们不同于函数对象，因为它们不包含对其全局执行环境的引用。 代码对象由内置的 <a class="reference internal" href="functions.html#compile" title="compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">compile()</span></code></a> 函数返回，并可通过从函数对象的 <code class="xref py py-attr docutils literal notranslate"><span class="pre">__code__</span></code> 属性从中提取。 另请参阅 <a class="reference internal" href="code.html#module-code" title="code: Facilities to implement read-eval-print loops."><code class="xref py py-mod docutils literal notranslate"><span class="pre">code</span></code></a> 模块。</p>
<p id="index-56">可以通过将代码对象（而非源码字符串）传给 <a class="reference internal" href="functions.html#exec" title="exec"><code class="xref py py-func docutils literal notranslate"><span class="pre">exec()</span></code></a> 或 <a class="reference internal" href="functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a> 内置函数来执行或求值。</p>
<p>更多信息请参阅 <a class="reference internal" href="../reference/datamodel.html#types"><span class="std std-ref">标准类型层级结构</span></a>。</p>
</div>
<div class="section" id="type-objects">
<span id="bltin-type-objects"></span><h3>类型对象<a class="headerlink" href="#type-objects" title="永久链接至标题">¶</a></h3>
<p id="index-57">类型对象表示各种对象类型。 对象的类型可通过内置函数 <a class="reference internal" href="functions.html#type" title="type"><code class="xref py py-func docutils literal notranslate"><span class="pre">type()</span></code></a> 来获取。 类型没有特殊的操作。 标准库模块 <a class="reference internal" href="types.html#module-types" title="types: Names for built-in types."><code class="xref py py-mod docutils literal notranslate"><span class="pre">types</span></code></a> 定义了所有标准内置类型的名称。</p>
<p>类型以这样的写法来表示: <code class="docutils literal notranslate"><span class="pre">&lt;class</span> <span class="pre">'int'&gt;</span></code>。</p>
</div>
<div class="section" id="the-null-object">
<span id="bltin-null-object"></span><h3>空对象<a class="headerlink" href="#the-null-object" title="永久链接至标题">¶</a></h3>
<p>此对象会由不显式地返回值的函数所返回。 它不支持任何特殊的操作。 空对象只有一种值 <code class="docutils literal notranslate"><span class="pre">None</span></code> (这是个内置名称)。 <code class="docutils literal notranslate"><span class="pre">type(None)()</span></code> 会生成同一个单例。</p>
<p>该对象的写法为 <code class="docutils literal notranslate"><span class="pre">None</span></code>。</p>
</div>
<div class="section" id="the-ellipsis-object">
<span id="bltin-ellipsis-object"></span><span id="index-58"></span><h3>省略符对象<a class="headerlink" href="#the-ellipsis-object" title="永久链接至标题">¶</a></h3>
<p>此对象常被用于切片 (参见 <a class="reference internal" href="../reference/expressions.html#slicings"><span class="std std-ref">切片</span></a>)。 它不支持任何特殊的操作。 省略符对象只有一种值 <a class="reference internal" href="constants.html#Ellipsis" title="Ellipsis"><code class="xref py py-const docutils literal notranslate"><span class="pre">Ellipsis</span></code></a> (这是个内置名称)。 <code class="docutils literal notranslate"><span class="pre">type(Ellipsis)()</span></code> 会生成 <a class="reference internal" href="constants.html#Ellipsis" title="Ellipsis"><code class="xref py py-const docutils literal notranslate"><span class="pre">Ellipsis</span></code></a> 单例。</p>
<p>该对象的写法为 <code class="docutils literal notranslate"><span class="pre">Ellipsis</span></code> 或 <code class="docutils literal notranslate"><span class="pre">...</span></code>。</p>
</div>
<div class="section" id="the-notimplemented-object">
<span id="bltin-notimplemented-object"></span><h3>未实现对象<a class="headerlink" href="#the-notimplemented-object" title="永久链接至标题">¶</a></h3>
<p>此对象会被作为比较和二元运算被应用于它们所不支持的类型时的返回值。 请参阅 <a class="reference internal" href="../reference/expressions.html#comparisons"><span class="std std-ref">比较运算</span></a> 了解更多信息。 未实现对象只有一种值 <code class="docutils literal notranslate"><span class="pre">NotImplemented</span></code>。 <code class="docutils literal notranslate"><span class="pre">type(NotImplemented)()</span></code> 会生成这个单例。</p>
<p>该对象的写法为 <code class="docutils literal notranslate"><span class="pre">NotImplemented</span></code>。</p>
</div>
<div class="section" id="boolean-values">
<span id="bltin-boolean-values"></span><h3>布尔值<a class="headerlink" href="#boolean-values" title="永久链接至标题">¶</a></h3>
<p>布尔值是两个常量对象 <code class="docutils literal notranslate"><span class="pre">False</span></code> 和 <code class="docutils literal notranslate"><span class="pre">True</span></code>。 它们被用来表示逻辑上的真假（不过其他值也可被当作真值或假值）。 在数字类的上下文中（例如被用作算术运算符的参数时），它们的行为分别类似于整数 0 和 1。 内置函数 <a class="reference internal" href="functions.html#bool" title="bool"><code class="xref py py-func docutils literal notranslate"><span class="pre">bool()</span></code></a> 可被用来将任意值转换为布尔值，只要该值可被解析为一个逻辑值（参见之前的 <a class="reference internal" href="#truth"><span class="std std-ref">逻辑值检测</span></a> 部分）。</p>
<p id="index-59">该对象的写法分别为 <code class="docutils literal notranslate"><span class="pre">False</span></code> 和 <code class="docutils literal notranslate"><span class="pre">True</span></code>。</p>
</div>
<div class="section" id="internal-objects">
<span id="typesinternal"></span><h3>内部对象<a class="headerlink" href="#internal-objects" title="永久链接至标题">¶</a></h3>
<p>有关此对象的信息请参阅 <a class="reference internal" href="../reference/datamodel.html#types"><span class="std std-ref">标准类型层级结构</span></a>。 其中描述了栈帧对象、回溯对象以及切片对象等等。</p>
</div>
</div>
<div class="section" id="special-attributes">
<span id="specialattrs"></span><h2>特殊属性<a class="headerlink" href="#special-attributes" title="永久链接至标题">¶</a></h2>
<p>语言实现为部分对象类型添加了一些特殊的只读属性，它们具有各自的作用。 其中一些并不会被 <a class="reference internal" href="functions.html#dir" title="dir"><code class="xref py py-func docutils literal notranslate"><span class="pre">dir()</span></code></a> 内置函数所列出。</p>
<dl class="attribute">
<dt id="object.__dict__">
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__dict__</code><a class="headerlink" href="#object.__dict__" title="永久链接至目标">¶</a></dt>
<dd><p>一个字典或其他类型的映射对象，用于存储对象的（可写）属性。</p>
</dd></dl>

<dl class="attribute">
<dt id="instance.__class__">
<code class="sig-prename descclassname">instance.</code><code class="sig-name descname">__class__</code><a class="headerlink" href="#instance.__class__" title="永久链接至目标">¶</a></dt>
<dd><p>类实例所属的类。</p>
</dd></dl>

<dl class="attribute">
<dt id="class.__bases__">
<code class="sig-prename descclassname">class.</code><code class="sig-name descname">__bases__</code><a class="headerlink" href="#class.__bases__" title="永久链接至目标">¶</a></dt>
<dd><p>由类对象的基类所组成的元组。</p>
</dd></dl>

<dl class="attribute">
<dt id="definition.__name__">
<code class="sig-prename descclassname">definition.</code><code class="sig-name descname">__name__</code><a class="headerlink" href="#definition.__name__" title="永久链接至目标">¶</a></dt>
<dd><p>类、函数、方法、描述器或生成器实例的名称。</p>
</dd></dl>

<dl class="attribute">
<dt id="definition.__qualname__">
<code class="sig-prename descclassname">definition.</code><code class="sig-name descname">__qualname__</code><a class="headerlink" href="#definition.__qualname__" title="永久链接至目标">¶</a></dt>
<dd><p>类、函数、方法、描述器或生成器实例的 <a class="reference internal" href="../glossary.html#term-qualified-name"><span class="xref std std-term">qualified name</span></a>。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.3 新版功能.</span></p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="class.__mro__">
<code class="sig-prename descclassname">class.</code><code class="sig-name descname">__mro__</code><a class="headerlink" href="#class.__mro__" title="永久链接至目标">¶</a></dt>
<dd><p>此属性是由类组成的元组，在方法解析期间会基于它来查找基类。</p>
</dd></dl>

<dl class="method">
<dt id="class.mro">
<code class="sig-prename descclassname">class.</code><code class="sig-name descname">mro</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#class.mro" title="永久链接至目标">¶</a></dt>
<dd><p>此方法可被一个元类来重载，以为其实例定制方法解析顺序。 它会在类实例化时被调用，其结果存储于 <a class="reference internal" href="#class.__mro__" title="class.__mro__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__mro__</span></code></a> 之中。</p>
</dd></dl>

<dl class="method">
<dt id="class.__subclasses__">
<code class="sig-prename descclassname">class.</code><code class="sig-name descname">__subclasses__</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#class.__subclasses__" title="永久链接至目标">¶</a></dt>
<dd><p>每个类会保存由对其直接子类的弱引用组成的列表。 此方法将返回一个由仍然存在的所有此类引用组成的列表。 例如:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">int</span><span class="o">.</span><span class="n">__subclasses__</span><span class="p">()</span>
<span class="go">[&lt;class &#39;bool&#39;&gt;]</span>
</pre></div>
</div>
</dd></dl>

<p class="rubric">备注</p>
<dl class="footnote brackets">
<dt class="label" id="id12"><span class="brackets"><a class="fn-backref" href="#id1">1</a></span></dt>
<dd><p>有关这些特殊方法的额外信息可参看 Python 参考指南 (<a class="reference internal" href="../reference/datamodel.html#customization"><span class="std std-ref">基本定制</span></a>)。</p>
</dd>
<dt class="label" id="id13"><span class="brackets"><a class="fn-backref" href="#id2">2</a></span></dt>
<dd><p>作为结果，列表 <code class="docutils literal notranslate"><span class="pre">[1,</span> <span class="pre">2]</span></code> 与 <code class="docutils literal notranslate"><span class="pre">[1.0,</span> <span class="pre">2.0]</span></code> 是相等的，元组的情况也类似。</p>
</dd>
<dt class="label" id="id14"><span class="brackets"><a class="fn-backref" href="#id4">3</a></span></dt>
<dd><p>它们必须如此，因为解析器无法区分这些操作数的类型。</p>
</dd>
<dt class="label" id="id15"><span class="brackets">4</span><span class="fn-backref">(<a href="#id6">1</a>,<a href="#id7">2</a>,<a href="#id8">3</a>,<a href="#id9">4</a>)</span></dt>
<dd><p>区分大小写的字符是指所属一般类别属性为 &quot;Lu&quot; (Letter, uppercase), &quot;Ll&quot; (Letter, lowercase) 或 &quot;Lt&quot; (Letter, titlecase) 之一的字符。</p>
</dd>
<dt class="label" id="id16"><span class="brackets">5</span><span class="fn-backref">(<a href="#id10">1</a>,<a href="#id11">2</a>)</span></dt>
<dd><p>要格式化单独一个元组，那么你应当提供一个单例元组，其唯一的元素就是要被格式化的元组。</p>
</dd>
</dl>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">目录</a></h3>
  <ul>
<li><a class="reference internal" href="#">内置类型</a><ul>
<li><a class="reference internal" href="#truth-value-testing">逻辑值检测</a></li>
<li><a class="reference internal" href="#boolean-operations-and-or-not">布尔运算 --- <code class="xref std std-keyword docutils literal notranslate"><span class="pre">and</span></code>, <code class="xref std std-keyword docutils literal notranslate"><span class="pre">or</span></code>, <code class="xref std std-keyword docutils literal notranslate"><span class="pre">not</span></code></a></li>
<li><a class="reference internal" href="#comparisons">比较运算</a></li>
<li><a class="reference internal" href="#numeric-types-int-float-complex">数字类型 --- <code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code>, <code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code>, <code class="xref py py-class docutils literal notranslate"><span class="pre">complex</span></code></a><ul>
<li><a class="reference internal" href="#bitwise-operations-on-integer-types">整数类型的按位运算</a></li>
<li><a class="reference internal" href="#additional-methods-on-integer-types">整数类型的附加方法</a></li>
<li><a class="reference internal" href="#additional-methods-on-float">浮点类型的附加方法</a></li>
<li><a class="reference internal" href="#hashing-of-numeric-types">数字类型的哈希运算</a></li>
</ul>
</li>
<li><a class="reference internal" href="#iterator-types">迭代器类型</a><ul>
<li><a class="reference internal" href="#generator-types">生成器类型</a></li>
</ul>
</li>
<li><a class="reference internal" href="#sequence-types-list-tuple-range">序列类型 --- <code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code>, <code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code>, <code class="xref py py-class docutils literal notranslate"><span class="pre">range</span></code></a><ul>
<li><a class="reference internal" href="#common-sequence-operations">通用序列操作</a></li>
<li><a class="reference internal" href="#immutable-sequence-types">不可变序列类型</a></li>
<li><a class="reference internal" href="#mutable-sequence-types">可变序列类型</a></li>
<li><a class="reference internal" href="#lists">列表</a></li>
<li><a class="reference internal" href="#tuples">元组</a></li>
<li><a class="reference internal" href="#ranges">range 对象</a></li>
</ul>
</li>
<li><a class="reference internal" href="#text-sequence-type-str">文本序列类型 --- <code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a><ul>
<li><a class="reference internal" href="#string-methods">字符串的方法</a></li>
<li><a class="reference internal" href="#printf-style-string-formatting"><code class="docutils literal notranslate"><span class="pre">printf</span></code> 风格的字符串格式化</a></li>
</ul>
</li>
<li><a class="reference internal" href="#binary-sequence-types-bytes-bytearray-memoryview">二进制序列类型 --- <code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code>, <code class="xref py py-class docutils literal notranslate"><span class="pre">bytearray</span></code>, <code class="xref py py-class docutils literal notranslate"><span class="pre">memoryview</span></code></a><ul>
<li><a class="reference internal" href="#bytes-objects">bytes 对象</a></li>
<li><a class="reference internal" href="#bytearray-objects">bytearray 对象</a></li>
<li><a class="reference internal" href="#bytes-and-bytearray-operations">bytes 和 bytearray 操作</a></li>
<li><a class="reference internal" href="#printf-style-bytes-formatting"><code class="docutils literal notranslate"><span class="pre">printf</span></code> 风格的字节串格式化</a></li>
<li><a class="reference internal" href="#memory-views">内存视图</a></li>
</ul>
</li>
<li><a class="reference internal" href="#set-types-set-frozenset">集合类型 --- <code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code>, <code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a></li>
<li><a class="reference internal" href="#mapping-types-dict">映射类型 --- <code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a><ul>
<li><a class="reference internal" href="#dictionary-view-objects">字典视图对象</a></li>
</ul>
</li>
<li><a class="reference internal" href="#context-manager-types">上下文管理器类型</a></li>
<li><a class="reference internal" href="#other-built-in-types">其他内置类型</a><ul>
<li><a class="reference internal" href="#modules">模块</a></li>
<li><a class="reference internal" href="#classes-and-class-instances">类与类实例</a></li>
<li><a class="reference internal" href="#functions">函数</a></li>
<li><a class="reference internal" href="#methods">方法</a></li>
<li><a class="reference internal" href="#code-objects">代码对象</a></li>
<li><a class="reference internal" href="#type-objects">类型对象</a></li>
<li><a class="reference internal" href="#the-null-object">空对象</a></li>
<li><a class="reference internal" href="#the-ellipsis-object">省略符对象</a></li>
<li><a class="reference internal" href="#the-notimplemented-object">未实现对象</a></li>
<li><a class="reference internal" href="#boolean-values">布尔值</a></li>
<li><a class="reference internal" href="#internal-objects">内部对象</a></li>
</ul>
</li>
<li><a class="reference internal" href="#special-attributes">特殊属性</a></li>
</ul>
</li>
</ul>

  <h4>上一个主题</h4>
  <p class="topless"><a href="constants.html"
                        title="上一章">内置常量</a></p>
  <h4>下一个主题</h4>
  <p class="topless"><a href="exceptions.html"
                        title="下一章">内置异常</a></p>
  <div role="note" aria-label="source link">
    <h3>本页</h3>
    <ul class="this-page-menu">
      <li><a href="../bugs.html">提交 Bug</a></li>
      <li>
        <a href="https://github.com/python/cpython/blob/3.7/Doc/library/stdtypes.rst"
            rel="nofollow">显示源代码
        </a>
      </li>
    </ul>
  </div>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>导航</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="总目录"
             >索引</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python 模块索引"
             >模块</a> |</li>
        <li class="right" >
          <a href="exceptions.html" title="内置异常"
             >下一页</a> |</li>
        <li class="right" >
          <a href="constants.html" title="内置常量"
             >上一页</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">3.7.8 Documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python 标准库</a> &#187;</li>
    <li class="right">
        

    <div class="inline-search" style="display: none" role="search">
        <form class="inline-search" action="../search.html" method="get">
          <input placeholder="快速搜索" type="text" name="q" />
          <input type="submit" value="转向" />
          <input type="hidden" name="check_keywords" value="yes" />
          <input type="hidden" name="area" value="default" />
        </form>
    </div>
    <script type="text/javascript">$('.inline-search').show(0);</script>
         |
    </li>

      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">版权所有</a> 2001-2020, Python Software Foundation.
    <br />
    Python 软件基金会是一个非盈利组织。
    <a href="https://www.python.org/psf/donations/">请捐助。</a>
    <br />
    最后更新于 6月 29, 2020.
    <a href="../bugs.html">发现了问题</a>？
    <br />
    使用<a href="http://sphinx.pocoo.org/">Sphinx</a>2.3.1 创建。
    </div>

  </body>
</html>